Assign a div event when it is fully loaded

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

+6
javascript jquery
source share
5 answers

You don’t know how you dynamically add your content, but this example should show how it can work.

Used by .append() to simulate your dynamically loaded content. Then, after adding it, it uses .find() to search for images and .load() to attach a load handler to them.

Finally, it returns the length property of the images. Then, in the load handler, when image loading ends, the length decreases. As soon as it reaches 0 , all images will be loaded, and the code inside if() will be launched.

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; 

Thus, the code only works on images in #mydiv .

If there are any images there that were not dynamic, and therefore should not receive the .load() event, you should be able to add a .not() filter to exclude those complete true properties.

Put this after .find() and before .load() .

 .not(function(){return this.complete}) 
+6
source share

It's hard to check it on just one div, but can I suggest using $(window).load() to check if all the images are loaded?

UPDATE: If you are using ajax, use the callback to see when json has loaded, then add $ ("div # id img"). Load () to see when all images are loaded. Only problem is that I noticed when the image is cached, the bootloader does not start. :(

+1
source share

If this is just the one image you want to wait for, you can load the image using ajax and then fire the event in the ajax callback.

+1
source share

To add to the idea of ​​the Shadow Wizard, you can 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 }); } }); 
+1
source share

Catch the onload event for all images in the div, there raise some global counter by 1. If this counter is equal to the number of images in the div ... all the images have finished loading. It should be just using jQuery.

This will only work for images, but other elements do not have an onload event.

0
source share

All Articles