Darryl Hein
Darryl Hein

Reputation: 144937

Is there a way to determine when 4 images have been loaded using JS?

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" />

Upvotes: 2

Views: 260

Answers (2)

Andreas Grech
Andreas Grech

Reputation: 107950

As regards Salty's example, it's best to use a closure to avoid global variables, like such:

$("img").load(function() {    
    var count = 0, numImages = $("img").size();

    return function () {
        if (++count === numImages) { 
            //All images have loaded    
        }
    };
}());

[Edit]

As per jeroen's comment, I replaced the hardcoded value of 4 (count === 4) with the jQuery size function as to allow for more flexibility within the function.

Upvotes: 8

Salty
Salty

Reputation: 6688

count=0;
$("img").load(function() {
    count++;
    if(count==4) { //All images have loaded
        //Do something!
    }
});

Upvotes: 3

Related Questions