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!
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();
});
});
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();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With