views:

138

answers:

2

I have 4 images on a page. I want to trigger a JS event once all 4 images are loaded. I of course can't be sure which order the images will be loaded in, so I can't trigger the event on the last image. One thought was to have a counter, but I can't think of the best way to check when that counter is equal to 4 as I don't like the idea of a setTimeout() checking every 200ms.

Any other ideas?

I'm using jQuery on the site, so I'm thinking that might be some help.

This is the image HTML code:

<img src="/images/hp_image-1.jpg" width="553" height="180" id="featureImg1" />
<img src="/images/hp_image-2.jpg" width="553" height="180" id="featureImg2" />
<img src="/images/hp_image-3.jpg" width="553" height="180" id="featureImg3" />
<img src="/images/hp_image-4.jpg" width="553" height="180" id="featureImg4" />
+3  A: 
count=0;
$("img").load(function() {
    count++;
    if(count==4) { //All images have loaded
        //Do something!
    }
});
Salty
+7  A: 

As regards Salty's example, it's best to use a closure as to not clubber space with global variables, like such:

$("img").load(function() {    
    var count = 0;
    var noImages = $("img").size();
    return function () {
        count++; 
        if(count === noImages) { 
            //All images have loaded    
        }
    };
}());

[Edit]

Changed the hardcoded value of 4 (count === 4) to the jQuery size function, as to allow more flexibility in the function. (thanks to jeroen's comment)

Andreas Grech
Unless these are the only four images on your page, however, you'll want to assign them a class or otherwise have some way to select just those four from your document. (e.g. `$("img.dynloaded").load(…)`)
Ben Blank
Yes exactly, because the $("img") selector is selecting every <img> tag on the page
Andreas Grech
Thanks, just what I needed, in combination with: var noImages = $("img").size(); instead of 4 to make it more flexible...
jeroen
jeroen, thanks for the comment; I updated the function now ;-)
Andreas Grech