assign event to div when it has loaded fully - javascript

Can I assign an event to a div to fire when all elements of the containing div have loaded fully? eg. if the div contains an image, fire an event on the div when the image has loaded fully. I am using jquery.

Not sure how you're dynamically adding your content, but this example should illustrate how it could work.
It is using .append() to simulate your dynamically loaded content. Then after the append, it uses .find() to find the images, and .load() to attach a load handler to them.
Finally, it returns the length property of the images. Then in the load handler, as the images finish loading, the length is decremented. Once it gets to 0, all the images are loaded, and the code inside the if() runs.
Example: http://jsfiddle.net/ehwyF/
var len = $('#mydiv').append('<img src = "http://dummyimage.com/150x90/f00/fff.png&text=my+image" /><img src = "http://dummyimage.com/160x90/f00/fff.png&text=my+image" /><img src = "http://dummyimage.com/170x90/f00/fff.png&text=my+image" /><img src = "http://dummyimage.com/180x90/f00/fff.png&text=my+image" />')
.find('img')
.load(function() {
if( --len === 0) {
alert('all are loaded');
}
}).length;
This way, the code runs based only on the images in #mydiv.
If there are any images in there that were not dynamic, and therefore shouldn't get the .load() event, you should be able to add a .not() filter to exclude ones the complete property is true.
Place this after the .find() and before the .load().
.not(function(){return this.complete})

If it's just one image you're wanting to wait for you can load the image with ajax and then trigger the event in the ajax callback.

It's hard to check it for just one div, but may I suggest using $(window).load() to check if all the images have loaded?
UPDATE:
If you using ajax then use the callback to see when the json has loaded, and then attach $("div#id img").load() to see when all the images have loaded. Only problem with this is that I have noticed when the image is cached, the loader does not get triggered. :(

To add to Shadow Wizard's idea, you could try the following code:
var totalImages = $(".yourImageClass").length;
var loadedImages = 0;
$(".yourImageClass").bind("onload", function() {
loadedImages++;
if (loadedImages == totalImages) {
//all images have loaded - bind event to DIV now
$("#yourDiv").bind(eventType, function() {
//code to attach
});
}
});

Catch the onload event of all images in the div, in there raise some global counter by 1. If that counter is equal to the amount of images in the div... all images finished loading.
Should be simple using jQuery.
This will work only for images though, other elements don't have onload event.

Related

Why does addEventListener for load event not work with a div?

When adding an event listener for the load I can't just use a function literal like I do for the click event. Why can't I use a function literal like I do for my click event?
<body>
<div>some content</div>
<script>
var div = document.getElementsByTagName("div")[0];
// does not work (console is not written to when page loads)...
div.addEventListener("load", function(){console.log("div load event")}, false);
// works (console is written to when div content is clicked...
div.addEventListener("click", function(){console.log("div click event")}, false);
</script>
</body>
The load event fires in elements which load external contents, such as img, iframe, etc.
The truth is load event may not fire case a content load before the event is declared. So, if you want the load event to work, you need to declare it before a src or href, for example.
Once the div is declared it's already loaded. So it's impossible to fire a event like this in the div.
If you want to know the div, including its elements such as img have loaded, you must declare the load event for each, i.e:
var loaded = 0;
var images = div.getElementsByTagName("img"),
len = images.length;
function imgload() {
if(++loaded > len) {
console.log("Div loaded.");
}
}
for(var i = 0, img; img = images[i]; i++) img.addEventListener("load", loaded);
When you add JS code for load event. Your load for div already finished. So load event will never be fired. And click works because it will appear later on when user click it.
Read this to get better understanding.
https://developer.mozilla.org/en-US/docs/Web/Events/load

jQuery .html function with .load

I am loading HTML content using jQuery's .html() function. Part of the HTML content I am trying to load are images, which take some time to be loaded. What I do is on an onclick event,
$('div').on('click',function() {
$('html').fadeOut(1000)
.html(content)
.load(function() {
$('html').fadeIn(1000)
});
});
What I wanted to happen is that, when the DOM has finished loading, I want it to fadeIn. If it is still not finished, I want it to stay hidden hence, the fadeOut function before the html load.
Is this possible? That method doesn't seem to work for me.
First, if you are replacing the entire HTML element, you might as well just do a full request cycle. That's essentially what you're going to end up with and it will be easier to hook to the window load event using a full request than to handle this with AJAX. If you're not replacing the entire page, then you've got your selector wrong.
Second, if you are just loading the DIV, then you can try hiding the DIV, binding the load event to it, then loading it with content. See the caveats for the http://api.jquery.com/load-event/ method for more information.
$('div').on('click',function() {
var $this = $(this); // save reference for future use
$this.fadeOut(1000) // hide
.load(function() { // hook up handler
$this.fadeIn(1000)
})
.html(content); // load content
});

javascript img onload()

I am using <img> onload function to trigger the resize action on the image that has been loaded. But I found if in one webpage there is two or more <img>s with the same "src", which means the image is the same, the latter <img>'s onload() function will not be invoked. How to make sure that all the <img>s are properly resized even when there are some <img>s with the same src?
Thanks.
This is happening because your browser is actually caching the first image. So when you attempt to load the same "src" again, it's cached locally and never actually fires an onload. To get it to load at all times, you could append on a unique value to the query string.
Instead of using a separate onload handler for each <img/>, why not just use a single onload event for the window? This event fires after everything (like all the images) have loaded, so you could just process each image in that single handler. Something like:
function processAllImages()
{
var imgElts = document.getElementsByTagName('img');
for (var i=0; i<imgElts.length; i++)
{
processImage(imgElts[i]); // TODO write this function
}
}
window.onload = processAllImages;
I asked similar question before. Check this out: Javascript/jQuery: How to detect img is fully downloaded or not?
In short, you can use 'complete' property of img tag.
check it before you bind load event.

how to handle onLoad Event on img tag and others

how to handle onLoad Event on img tag?
example:
$ ('img'). onload (function (e) {
alert ('image loaded' + $ (this), attr ('src'));
})
is like the imageLoader
and others tags like script, link, etc...
jQuery callback on image load (even when the image is cached)
$("img").one('load', function() {
// do stuff
}).each(function() {
if(this.complete) $(this).load();
});
Seems to work for me, and should fix the caveat with caching.
There's an example of how to do this right on the jQuery doc page for .load().
HTML:
<img src="book.png" alt="Book" id="book" />
Javascript:
$('#book').load(function() {
// Handler for .load() called.
});
And, there are a bunch of caveats to watch out for listed on that jQuery page too.
With images, if you want to assure that the load handler gets called, the load handler has to be set before the image can possibly be loaded. If you're constructing the image in code, that means you have to set the load handler before you set the .src attribute. That's because, in some browsers, if the image is in the memory/disk cache, it will load immediately when you assign .src and if you then subsequently set the .load() handler, you will be too late (the image will already be loaded) and the .load() handler will never be called.
I don't know how to guarantee that a jQuery-based .load() always gets called for an image that's in your page HTML because you can't assign the event handler until the object exists, but once the object it exits, it might already be loaded. You can use non-jQuery setting of an onload=xxx in the actual HTML though that is an older style of coding. Of course, you can always hook window.onload to know when all page images (and other resources) have been loaded.
jQuery has a load method, not onload. And your code should probably be:
$ ('img').load(function () {
alert('image loaded ' + this.src);
})

Javascript/jQuery HasLoaded or equivalent?

I know in jquery it is possible to call the javascript/jquery onload()/load() functions on, for example an image (<img>).
However, if in jquery if i use .html(htmlString) to insert an image after the dom has loaded, how can i add a listener to handle the images onload event? Is there a property I can check to see various images and if they have loaded?
After appending your html, you can bind the load event to the contained images:
$("#foo").html(htmlString).find("img").one("load", function() {
...
}).each(function() {
// image has been cached, so load event won't fire unless we explicitly call it
if(this.complete) $(this).trigger("load");
});
Check the complete property of the image(s)

Categories