parte bena
parte bena

Reputation: 25

make imagesloaded on jquery fade in individual images

This is the sample html structure:

<div class=container>
    <div class=green></div>
    <div class=green></div>
    <div class=green></div>
    <div class=green></div>
</div>

The below code works:

 $('.container').imagesLoaded(function(){
    $('.green').find('img').fadeIn(444);
});

The only drawback is that it waits for all images loaded, then fades them in at the same time. How can i make each images load as soon as it has finished loading instead of waiting for all of them to load.

I have tried this but it does not work:

    $('.green').imagesLoaded(function(){                    
        $(this).find('img').fadeIn(444);
    });

Upvotes: 1

Views: 1013

Answers (3)

Andy
Andy

Reputation: 4778

I have had the same problem and found you need to bind the imagesLoaded plugin to .green inside of an .each() method like so:

$('.container').find('.green').each(function () {
    var _this = $(this);

    _this.imagesLoaded(function () {
        _this.find('img').fadeIn(444);
    });
});

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

try something like::

jQuery.fn.eachLoaded = function(fn){
   return this.each(function(){
     // if already loaded call callback
     if (this.complete || this.readyState == 'complete'){
       fn.call(this);
     } else { // otherwise bind onload event
       $(this).load(fn);
     }
   });
}
$('.green img').eachLoaded(function(){
  $(this).fadeIn(444)
});

Upvotes: 0

Viral Shah
Viral Shah

Reputation: 2246

Yeah, this is typically a fairly basic problem: some images finish loading before you've assigned them a load event handler. This is especially likely when the images are cached.

If the images are in the HTML the only reliable way is, unfortunately, to include an (extremely ugly) inline onload attribute:

<img src="..." alt="..." onload="$(this).fadeIn();">

Upvotes: 0

Related Questions