Dave Stibrany
Dave Stibrany

Reputation: 2389

jQuery .delay() in animation loops

I'm trying to do some basic animation with jQuery. I want to fade in a few elements, but I would like to fade in, the 2nd element while the 1st one is halfway done, the 3rd while the 2nd it halfway done, etc.

I know I can do something like this:

$('#element1).fadeIn(1000);
$('#element2).delay(500).fadeIn(1000);
$('#element3).delay(500).fadeIn(1000);
etc.

A loop seems more elegant though and my question is, why doesn't the following code work as I would expect?

for (var i = 1; i <= 5; i++;) {
    $('#box' + i).fadeIn(2000).delay(500);
}

I would expect a delay to occur between each loop iteration, but instead all animation happens in sync.

Where am I seeing this wrong?

Upvotes: 0

Views: 1591

Answers (1)

pepkin88
pepkin88

Reputation: 2756

Every element has its own effects queue. For every element there must be different delay value:

for (var i = 0; i < 5; i++) {
    $('#box' + (i + 1)).delay(500 * i).fadeIn(1000);
}

http://jsfiddle.net/cDcU7/1/

Upvotes: 3

Related Questions