views:

631

answers:

3

Hey,

I have a question regarding jQuery and image fading. I have a bunch of images and I would like to fade each one sequentially to full opacity when you load the page. My html code is below:

<div class='mod'>
   <img src='image-src' alt='' />
   <div class='mod-text'>
   <h2>Title</h2>
   <p>Caption</p></div>
</div>

<div class='mod'>
   <img src='image-src' alt='' />
   <div class='mod-text'>
   <h2>Title 2</h2>
   <p>Caption 2</p></div>
</div>

Each image has its own corresponding Title and Caption which is displayed one below the other. I would like to have the first image fade in first, then have each following image fade in after. Anybody have an idea? I have a very basic understanding of jQuery. Thanks

+1  A: 

This probably isn't something that you need to implement yourself, check out the jQuery Cycle Plugin.

Aaron Vernon
+2  A: 

You'll need to queue the animations and then start each when the previous ends:

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

var animations = new Array();
// queue all
$("img").each(function() {
    animations.push($(this));
});

// start animating
doAnimation(animations.shift());

function doAnimation(image) {
    image.fadeIn("slow", function() {
        // wait until animation is done and recurse if there are more animations
        if(animations.length > 0) doAnimation(animations.shift());
    });
}
Ariel
+1 for the added flexibility / predictability
Mef
+1  A: 

You can also fade them in sequentially by delaying the effect for each subsequent image like so (note: I'm using window.load to ensure all images are loaded before starting the animations):

$(window).load(function() {

        var delay = 0;

        $('img').each(function() {
            $(this).delay(delay).fadeIn();
            delay += 150;
        });

    });

This is great for overlapping the animations as opposed to waiting til each one completes. It can also be randomized like so:

$(window).load(function() {

        var delay = 0;

        $('img').sort(function() { return (Math.round(Math.random()) - 0.5); }).each(function() {
            $(this).delay(delay).fadeIn(600);
            delay += 150;
        });

    });
Derek Hunziker