Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fade in images staggered with jQuery

Tags:

jquery

I have a gallery page with many images that I would like to load one by one, or at least give the illusion that each one is fading in one by one.

I've come up with this:

 $(".fadeInImage").hide();

var counter = 0;
$(".fadeInImage").each(function() {
    counter = counter + 50;
    fade_in(this,counter);

});
function fade_in(obj,counter)
{
    $(obj).bind("load", function () { $(this).delay(counter).fadeIn(); });  
}

This works lovely, and also just loads the images normally if there is no js. But, my question is, as I'm not that expert with jQuery, is there any problems you can foresee? Is there a better way to do this?

Thanks in advance!

like image 898
Michael Watson Avatar asked Dec 22 '22 14:12

Michael Watson


2 Answers

Looks good to me. Although you could simplify it to something like this -- remember to use load event on window due to unpredictable nature of how long it'll take to load images:

$(document).ready(function() {
    $('.fadeInImage').hide();
});

$(window).load(function() {
    $(".fadeInImage").each(function(i) {
       $(this).delay((i + 1) * 50).fadeIn();
    });
});
like image 79
Gary Green Avatar answered Jan 07 '23 11:01

Gary Green


You can't guarantee that the images will load in the order they appear in the HTML (especially if their sizes differ) so you may not get a smooth fade-...-fade transition. You can use the window's load event to get them to fade in when everything is ready:

$(".fadeInImage").hide();

$(window).load(function () {
    var counter = 0;
    $(".fadeInImage").each(function() {
        counter = counter + 50;

        $(this).delay(counter).fadeIn();
    });
});
like image 35
Tom Hennigan Avatar answered Jan 07 '23 11:01

Tom Hennigan