Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

All images onload in jQuery?

I have two <img>s:

<img src="photo1.png">
<img src="photo2.png">

and I want it to run a function when both of them are finished loading.

$("img").load(blah);
function blah(e){
    var blah = "text";
}

But it doesn't work. It fires two times, since jQuery add onload to <img>s separately, which is not I wanted.

So how can I do that? Please help.

Upvotes: 1

Views: 749

Answers (1)

David Rodrigues
David Rodrigues

Reputation: 12532

You can try it:

var imgs = $('img');
var imgs_count = imgs.length;
var imgs_loaded = 0;

imgs.load(function() {
    imgs_loaded++;

    if(imgs_loaded === imgs_count) {
        alert('All loaded!');
    }
});

Upvotes: 5

Related Questions