queued animations on multiple elements

3.3k views Asked by At

I'm trying to find out how to queue animations on multiple elements using jQuery.

For example, I need to move on element across the screen. Then when that is done, move the next one, etc.

This of perhaps a list of items.. that fall into place.. one by one.

Can somebody help me out?

Do I need to resort to using the onComplete functions of each animation to start the next one?

Update: simple example.

<ul><li>Item 1</li><li>Item 2</li><li>Item 3</li><li>Item 4</li></ul>

I want to make each of them fade in one by one. SO Item 1 fades in. Then when that is done, Item 2 fades in and so forth.

I'm converting some Flash "page build" type animations to HTML using jQuery. So I need to queue animations on multiple elements. Like make a box appear, and the slide some text onto it.. etc..

3

There are 3 answers

3
jAndy On

Actually all of jQuerys fx methods (including .animate()) offer a complete callback. That is when you need to execute some non-fx stuff after an animation has completed.

If you just want to have different fx effects executing in order, it's enough to chain the methods like

$('object').fadeOut(3000).slideDown(2500).slideUp(1500);

jQuery will automatically take care of you in this spot. This is translated into a call like

$('object').fadeOut(3000, function() {
    // do something here
    $(this).slideDown(2500, function() {
        // do something here
        $(this).slideUp(1500, function() {
           // do something here
        });
    });
});

update

In reference to your comment, enter this into your firebug or webkit console:

 $('div').slice(4, 9).fadeOut(3333).fadeIn(5555).slideUp(2000).slideDown(1000);

This would work on some upper div elements from the Stackoverflow side.

1
maid450 On

if you know the duration of the effects on the other elements you can add a delay for every element.

Say you want to fade out some divs one after the other, and each fade takes 800ms, then, you can start the first one right away, the second one with a delay of 800ms (so it starts when the other ends), the third one a delay of 1600ms and so on...

An automated example for this that you can execute with firebug or webkit console (liked your example idea jAndy! =D) is:

$('div.nav li').each(function(i, elem) {
    $(elem).delay(i * 800).fadeOut(800);
});

(execute it watching at the navigation links: Question, Tags, Users...)

0
Glenn Barnett On

Paul Irish wrote a great article on this topic:

http://paulirish.com/2008/sequentially-chain-your-callbacks-in-jquery-two-ways/

For your fade-in example, you could do:

(function showNext(jq){
jq.eq(0).fadeIn("fast", function(){
    (jq=jq.slice(1)).length && showNext(jq);
});
})($('ul > li'))

Adjust to taste.