Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Load all images inside div before display

I want to load every image inside a div before actually displaying them. I have something similar to this:

<div>

<img src="1.jpg" />
<img src="1.jpg" />
<img src="1.jpg" />
<img src="1.jpg" />
<img src="1.jpg" />
<img src="1.jpg" />

</div>

At first I tried doing things like:

$('div img').load(function() {

$('div img').show();


});

Or this:

$('div').find('img').load(function() {

$('div img').show();

});

Unfortunately, this didn't work because once the browser loads even just a single image, it fires the event. Any ideas on how to load everything first ? Thanks!

like image 628
AJ Naidas Avatar asked Feb 19 '23 22:02

AJ Naidas


2 Answers

You can keep track of how many images have loaded:

var $images = $('div img'),
    preloaded = 0,
    total = $images.length;
$images.load(function() {
    if (++preloaded === total) {
        // Done!
    }
});
like image 182
nathan Avatar answered Feb 21 '23 11:02

nathan


Unfortunately there is not easy way to do this in a cross browser compatible way. But luckily there are 2 plugins out there that can make it painless.

Check out waitforimages and imagesloaded

Then you can do:

$('div').waitForImages(function(){
  $(this).find('img').show();
});
like image 29
Fresheyeball Avatar answered Feb 21 '23 12:02

Fresheyeball