2

Ive been looking at a jquery solution that listens to when each image (out of a bunch) are loaded before executing some actions (fadein etc).

With imagesLoaded I've managed to do this when ALL images are loaded, but I would want it to execute on each image once its loaded independent of the state of the others.

I think this is possible with imagesLoaded, but havent managed to get that to work. Has anyone?

Other solution?

mipe34
  • 5,372
  • 3
  • 25
  • 37
John Anderson
  • 409
  • 1
  • 6
  • 13

5 Answers5

5

Listen to the imagesLoaded progress event.

(https://github.com/desandro/imagesloaded)

imagesLoaded("img").on("progress", function(imagesLoadedInstance, image) {
    // Code for each image
});
Johan Sundén
  • 447
  • 4
  • 9
0

You can attach a function directly to the DOM like: <img onload="executeThisImage(imgId);" /> ?

Or you can bind the load directly to it with jQuery like mipe34 suggests:

$("#myImage").load(function() { ... });
fmsf
  • 33,514
  • 48
  • 140
  • 190
0

Try this using jQuery:

$("#myImage").bind("load", function () { $(this).fadeIn(); });

or the same with different syntax:

$("#myImage").load(function(event) {
    $(this).fadeIn();
});

Also check this interesting topics on SO:

The second one is really interesting one. There is a solution how to make it working even when the image is cached by the browser.

Following the best answer on this topic. I see the best solution like:

$("#myImage").one('load', function() {
  $(this).fadeIn();
}).each(function() {
  if(this.complete) $(this).load();
});

Here is used one for event binding to assure that event handler is executed at most once. The each loop will assure that if image is cached it will fire the load event on it.

Community
  • 1
  • 1
mipe34
  • 5,372
  • 3
  • 25
  • 37
0

You could use jQuery load event for that:

$("img").load(function(event) {
    console.log(this);
});

It might be good idea to limit the code to some specific set of images. For example using a class:

$("img.foo").load(function(event) {
    console.log(this);
});
Mika Tuupola
  • 18,021
  • 5
  • 36
  • 45
0

For this to work, you first need to hide the image:

$('img').css('display', 'none');

Then fade it in when the load event fires:

$('img').load(function(){
    $(this).fadeIn();
});
thordarson
  • 4,684
  • 2
  • 15
  • 35