How to find out if html element got fully loaded? - javascript

i need to know when a special html element containing images has been fully loaded.
The problem with this html element is that it gets replaced fully in the DOM on button click.
What can i do? (i do not want to assign a handler to each of the containing images btw.)

pretty ugly, but working
var soManyImgsInHere = 0;
var fooAttachEvent = function(whereAreTheImages_Container){
var where = whereAreTheImages_Container; //shorthand
var length = where.length;
soManyImgsInHere = length;
var imgs = where.getElementsByTagName('img');
for(var i=0;i<length;i++){
imgs[i].onload = function(){
soManyImgsInHere--;
if(soManyImgsInHere == 0){
alert('all imgs fully loaded'); // do whatever you want here :) all images are now fully loaded
}
}
};
let's assume your images are in a div with the id "fooImages"
then simply use this function right under this div like that:
<div id="fooImages">
<img src="1.jpg" />
<img src="2.jpg" />
<img src="3.jpg" />
</div>
<script>fooAttachEvent(document.getElementById('fooImages'));</script>
Hope this helps :)

Related

JavaScript Text Replace

I'm using the code below to amend an image url (basically adding 'admin' to the start of the URL inside 'news' div. This works fine for what I'm trying to do, but it's causing some other problems, like blocking embedded Tweets and blocking some adverts from showing that are placed inside the 'news' div.
Is there a better way to achieve what I want that won't impact other code as I can't for the life of me understand why it's causing issues with other code, but removing the below fixes the issue with the tweets and ads?
function replaceText(){
var theDiv = document.getElementById("news");
var theText = theDiv .innerHTML;
theText = theText.replace(/ckfinder/g, 'admin/ckfinder');
theDiv.innerHTML = theText;
}
This is the image path I'm amending:
<img height="267" src="/ckfinder/userfiles/images/XXX/XXX.jpg" width="400" />
But need it to be:
<img height="267" src="admin/ckfinder/userfiles/images/XXX/XXX.jpg" width="400" />
You should be more specific and target the img tag and update the src attribute directly.
function replaceText() {
var images = document.querySelectorAll(".news img");
for (var i = 0; i < images.length; i++) {
var img = images[i];
img.src = img.src.replace(/ckfinder/g, 'admin/ckfinder');
}
}
window.onload = replaceText;
<div id="news">
<p>Don't want to update this ckfinder</p>
<img height="267" src="/ckfinder/userfiles/images/XXX/XXX.jpg" width="400" />
</div>

Remove image when clicked

Basically, I'm trying to create a game where the goal is to click on images so they disappear.
I've made a function that spawns one image on a random location on the screen. Then I've also made an interval so it spawns 15 images in random locations. Now I want the images to disappear when clicked on.
My thoughts on doing this were to make a "click" function, so if the images are clicked the "img.style.height = '0px';
However, I'm not getting this or anything to work.
Use
<img onclick="this.style.visibility = 'hidden'" src="..." />
if you want to leave the space occupied by the image, otherwise:
<img onclick="this.style.display = 'none'" src="..." />
If you need to remove the image from an array of objects, you need to define a function as well.
In your code:
img.setAttribute("onclick", "this.style.visibility = 'hidden'" );
or
img.setAttribute("onclick", "this.style.display = 'none'" );
After you insert all images in document, define a click listener for all images and hide images on click. A simple example here
function hide(el) {
el.style.display = 'none';
}
var imgs = document.getElementsByTagName("img");
for(let i = 0; i < imgs.length; i ++) {
imgs[i].addEventListener('click', function(e) {
hide(e.target);
});
}
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgYxw854mGOAp8f16evj_WYw_Ph385nUVygQdxHvuD9b3ueJxT0A" id="1" alt="Mountain View 1">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT8_MiTkMX9nLJ9udtnwOQekIrQwUQ9KMZiU4fLfI7YhXCyIGZn" id="2" alt="Mountain View 2">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRgR4KM-zrVRmfdGPf5bll9vq4uLw7FSLpTmHUf9-RkYZ92Ey8Q" id="3" alt="Mountain View 3">
Your code should change like this
function SpawnW() {
var img = document.createElement("img");
img.setAttribute("style", "position:absolute;");
img.setAttribute("src", "women3.png");
document.body.appendChild(img);
img.setAttribute("onclick", "this.style.display = 'none'");
// pictureNumber++;
}
SpawnW();
Hope this helps you.

Img src change on page load

I want JavaScript to load a few img src's on page load. However my solution doesn't seem to work.
Any help would be very appreciated.
HTML
<li><img id="option1" height="45px" width="75px" alt="" src=""></li>
<li><img id="option2" height="45px" width="75px" alt="" src=""></li>
JavaScript
function filltopfoto(){
var settoppic = new Image;
for (var i = 0; i <= itemlist;i++){
settoppic.src = 'img' + i + '.jpg';
$('option' + i).src = settoppic.src;
}
}
FYI:
itemlist contains the amount of images that need to be filled.
The script gets loaded on body load.
Here is the jsfiddle of the code below to show a real example.
images = ["image1/url", "image2/url"] // define image source urls
$(document).ready(function(){ // wait until the document is ready
for(var i = 0; i < images.length; i++) // loop over all images
$('#option'+(i+1)).attr('src', images[i]); // set the src attribute, note the '#'
});
A couple of your mistakes:
JQuery's $('#id') look-up requires the hashtag (#) for ids.
Your filltopfoto() function is never called (Try doing alert('hello!') inside the function).
Your $('options'+i) gives options0 and options1 -- you need options1 and options2
Not sure why you create a new Image just to store a src variable. You can remove this code.

Will images not load with the page if the image tags are written with javascript and require user input?

I wanted a way to load images only when needed but am hesitant to use AJAX. Instead, will something like this work?
<div onclick="loadimages()">Section Title</div>
<script type="text/javascript">
function loadimages()
{
document.write('<img src="images/thumbnail1.jpg" />');
document.write('<img src="images/thumbnail2.jpg" />');
document.write('<img src="images/thumbnail3.jpg" />');
}
</script>
The intent is for the images to appear below the "Section Title" when that div is clicked, and for the images to be loaded only at that time.
If you want to add elements to the DOM dynamically there are several choices much more preferable than the abhorrent document.write. For example, you can do this:
var image = document.createElement("img");
image.src = "images/thumbnail1.jpg";
var parent = document.getElementById("foo"); // identify the parent somehow
parent.appendChild(image);
Or you could do this:
var parent = document.getElementById("foo"); // identify the parent somehow
parent.innerHTML += '<img src="..." />';
Or, if you use jQuery:
$("your selector here").append('<img src="..." />');
Edit: Untested code -- typed on the fly.
document.write won't do what you want after the page has loaded, you'd have to do something with the DOM..
Like, perhaps:
<div id='section_title' onclick="loadimages()">Section Title</div>
<script type="text/javascript">
function loadimages()
{
var pics = ['thumbnail1.jpg', 'thumbnail2.jpg', 'thumbnail3.jpg'];
var i, img, el;
el = document.getElementById('section_title');
for (i = 0; i < pics.length; i++) {
img = document.createElement("img");
img.src = pics[i];
el.appendChild(div);
}
}
</script>
Another way would be to put the images in your HTML file, but with display:none to hide them and unhide as needed.
Or, depending on the purpose, put them in the HTML as normal, then hide them on load and unhide then when needed.
When you do document.write('something');
This something will replace entire contents of your document.
What you can do is, create new elements dynamically and append them at appropriate places.

Programmatically change the src of an img tag

How can I change the src attribute of an img tag using javascript?
<img src="../template/edit.png" name="edit-save" alt="Edit" />
at first I have a default src which is "../template/edit.png" and I wanted to change it with "../template/save.png" onclick.
UPDATED:
here's my html onclick:
<img src="../template/edit.png" id="edit-save" alt="Edit" />
and my JS
function edit()
{
var inputs = document.myform;
for(var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
}
I've tried inserting this inside the edit(), it works but need to click the image twice
var edit_save = document.getElementById("edit-save");
edit_save.onclick = function(){
this.src = "../template/save.png";
}
Give your img tag an id, then you can
document.getElementById("imageid").src="../template/save.png";
You can use both jquery and javascript method:
if you have two images for example:
<img class="image1" src="image1.jpg" alt="image">
<img class="image2" src="image2.jpg" alt="image">
1)Jquery Method->
$(".image2").attr("src","image1.jpg");
2)Javascript Method->
var image = document.getElementsByClassName("image2");
image.src = "image1.jpg"
For this type of issue jquery is the simple one to use.
if you use the JQuery library use this instruction:
$("#imageID").attr('src', 'srcImage.jpg');
its ok now
function edit()
{
var inputs = document.myform;
for(var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
var edit_save = document.getElementById("edit-save");
edit_save.src = "../template/save.png";
}
Give your image an id. Then you can do this in your javascript.
document.getElementById("blaah").src="blaah";
You can use this syntax to change the value of any attribute of any element.
<img src="../template/edit.png" name="edit-save" onclick="this.src = '../template/save.png'" />
With the snippet you provided (and without making assumptions about the parents of the element) you could get a reference to the image with
document.querySelector('img[name="edit-save"]');
and change the src with
document.querySelector('img[name="edit-save"]').src = "..."
so you could achieve the desired effect with
var img = document.querySelector('img[name="edit-save"]');
img.onclick = function() {
this.src = "..." // this is the reference to the image itself
};
otherwise, as other suggested, if you're in control of the code, it's better to assign an id to the image a get a reference with getElementById (since it's the fastest method to retrieve an element)
In this case, as you want to change the src of the first value of your element, you have no need to build up a function. You can change this right in the element:
<a href='#' onclick='this.firstChild.src="../template/save.png"')'>
<img src="../template/edit.png" id="edit-save"/>
</a>
You have several ways to do this. You can also create a function to automatize the process:
function changeSrc(p, t) { /* where p: Parent, t: ToSource */
p.firstChild.src = t
}
Then you can:
<a href='#' onclick='changeSrc(this, "../template/save.png");'>
<img src="../template/edit.png" id="edit-save"/>
</a>
Maybe because you have a tag like a parent of the tag.
That why you have to click two time the images.
For me the solution is this:
http://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_lightbulb

Categories