Evanss
Evanss

Reputation: 23142

jQuery animate each element but with a delay between each one

With the following I'm fading in and out a div on a loop that lasts forever.

function fadeOutFunc() {    
    $('.image-list .bottom').delay(5000).fadeOut(500).delay(5000).fadeIn(500,fadeOutFunc);
}
fadeOutFunc();

This is working fine but I need to change it a a bit. I have 4 divs that the selector targets. I want the first one to start animating after 5 seconds as it currently does. However I want the 2nd div to start animating after 6 seconds, the third div after 7 seconds, and the 4th div after 8 seconds.

The most scalable code would be one that would work even if there were more than 4 divs that matched the selector.

Upvotes: 1

Views: 1026

Answers (2)

Jono
Jono

Reputation: 4086

Use this to define the delay.

$('.image-list .bottom').each(function(index, item){ 
   var baseDelay = 5000;
   var delayDifference = 1000;
   delayForThisDiv = baseDelay + (index*delayDifference);
});

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337646

You need to loop through and increment the delay on each iteration. Try this:

$('.image-list .bottom').each(function(i) {
    var initialDelay = i * 1000 + 5000;
    $(this).delay(initialDelay).fadeOut(500).delay(5000).fadeIn(500,fadeOutFunc);
});

Upvotes: 1

Related Questions