How to wait for one jquery animation to finish before the next one begins?

Abe Miessler picture Abe Miessler · May 24, 2011 · Viewed 25.8k times · Source

I have the following jQuery:

$("#div1").animate({ width: '160' }, 200).animate({ width: 'toggle' }, 300 );
$("#div2").animate({ width: 'toggle' }, 300).animate({ width: '150' }, 200);

My issue is that both happen at the same time. I would like the div2 animation to start when the first one finishes. I've tried the method below, but it does the same thing:

$("#div1").animate({ width: '160' }, 200).animate({ width: 'toggle' }, 300, ShowDiv() );
....
function ShowDiv(){
   $("#div2").animate({ width: 'toggle' }, 300).animate({ width: '150' }, 200);
}

How can I make it wait for the first one to finish?

Answer

James Montagne picture James Montagne · May 24, 2011

http://api.jquery.com/animate/

animate has a "complete" function. You should place the 2nd animation in the complete function of the first.

EDIT: example http://jsfiddle.net/xgJns/

$("#div1").animate({opacity:.1},1000,function(){
    $("#div2").animate({opacity:.1},1000);    
});​