7

There is a div in which there will be some elements (images, iframe, etc) being loaded via Ajax. After those elements have been fully loaded, I need to execute a function for the div.

How do I determine if all elements in the div have been fully loaded?

I use jQuery as the library.

Ian Y.
  • 2,293
  • 6
  • 39
  • 55

2 Answers2

10

For images and iframes you can use load event:

// get all images and iframes
var $elems = $('#div').find('img, iframe');

// count them
var elemsCount = $elems.length;

// the loaded elements flag
var loadedCount = 0;

// attach the load event to elements
$elems.on('load', function () {
    // increase the loaded count 
    loadedCount++;

    // if loaded count flag is equal to elements count
    if (loadedCount == elemsCount) {
        // do what you want
        alert('elements loaded successfully');
    }
});

You should execute the above script after appending your elements via Ajax into your #div element.

dashtinejad
  • 6,193
  • 4
  • 28
  • 44
  • Not sure if I missed something, but the function doesn't seem to fire when the number of `img` and `iframe` is 0. – Ian Y. Oct 24 '14 at 06:22
  • 1
    @IanY. Yes, you are correct, You should check for that: `if (elemsCount == 0) { alert('no element at all'); }` – dashtinejad Oct 25 '14 at 05:12
1

Please elaborate your question. There are different methods for different type of elements.

For iframe follow this thread, How can I detect whether an iframe is loaded?

For image http://api.jquery.com/load-event/

for flash it depends lots of things. How can I tell if Flash is loaded on a website?

Community
  • 1
  • 1
brtb
  • 2,201
  • 6
  • 34
  • 53