1

Please view my previous question here:

Animate Divs One Right After the Other with Jquery

View my second answer....

Can anyone tell me how to write my code correctly so that i can animate more than just 2 divs? Please give me an example of at least 4 divs if you can. Thanks in advance.

Community
  • 1
  • 1
WillingLearner
  • 7,106
  • 6
  • 34
  • 51

1 Answers1

3

Give them a common class, iterate over them with .each(), and use .delay(), multiplying the current index number of the iteration by the duration.

Example: http://jsfiddle.net/patrick_dw/jPeAp/

html

<div class="animation">Hello!</div>
<div class="animation">Jquery Animate!</div>
<div class="animation">Hello!</div>
<div class="animation">Jquery Animate!</div>

js

$('.animation').each(function( index ) {
    $(this).delay( index * 700 ).fadeIn();
});

This way it will automatically work for any number of elements.

In the loop, index will be 0, 1, 2, etc.. So the delay will be 0, 700, 1400, etc.


EDIT:

If you can't give the elements a common class, then just group the IDs into one multiple selector.

$('#animation1,#animation2,#animation3,#animation4').each(function( index ) {
    $(this).delay( index * 700 ).fadeIn();
});
user113716
  • 318,772
  • 63
  • 451
  • 440
  • so what about if i have a bunch of totally different IDs then? – WillingLearner Dec 16 '10 at 14:25
  • @WillingLearner: That's why you use a class instead of an ID. If for some reason you can't assign a class, then just create a [multiple selector](http://api.jquery.com/multiple-selector/) with all the IDs. I'll update my answer to show how. – user113716 Dec 16 '10 at 14:30
  • what if i wanted to reverse the animation on a button press? – WillingLearner Jan 16 '11 at 07:16
  • 1
    @WillingLearner: It depends on what you mean by "reverse the animation". Do you mean fade them out from last to first? If so, you can `.get()` the Array of DOM elements, and `.reverse()` the order, then place them back in a jQuery object, and do the same as above. This doesn't reverse the order on the page. Just in the Array. [Here's an example.](http://jsfiddle.net/jPeAp/1/) – user113716 Jan 16 '11 at 13:32