lisovaccaro
lisovaccaro

Reputation: 33966

jQuery animations - when is asynchronous and when it's not?

I have two divs which I want to animate:

<div id="character">
  <div id="sprite"></div>
</div>

And I'm calling animate in jQuery like this:

$("#sprite").animate({"width" : "1", }, 400 );
$("#character").animate({"width" : "1", }, 400 );
$("#character").animate({"margin-left" : "0", }, 400 );

However it seems that the first two animations execute simultaneusly while the third only starts when the others have finished.

Why is asynchronous in the first two but not with the third? How can I make the three of them run at the same time?

Upvotes: 5

Views: 5258

Answers (3)

samura
samura

Reputation: 4395

the second $("#character").animate gets queued. If you have 2 $("#character") the second only happens when the first is complete. What you could do is:

$("#character").animate({"margin-left" : "0", "width" : "1", }, 400 );

to make both animations happen at the same time, or:

$("#character").animate({"width" : "1"}, {"duration":400, "queue": false});
$("#character").animate({"margin-left" : "0"}, {"duration":400, "queue": false});

Upvotes: 10

topek
topek

Reputation: 18979

Try:

$("#sprite").animate({"width" : "1", }, 400 );
$("#character").animate({"width" : "1", }, 400 );
$("#character").animate({"margin-left" : "0", }, {duration:400, queue:false} );

Otherwise jQuery will queue the animations, see the docs for animate

Upvotes: 4

James Montagne
James Montagne

Reputation: 78670

animate has an optional queue option which tells the animation whether or not to get added to the queue. If the animation is not queued, it will run immediately. Each element has its own queue, so $("#sprite") and $("#character") each have a separate animation queue.

If you want everything to just run immediately, use the queue option. If you need everything to be queued to the same queue, you will need to create your own queue. http://api.jquery.com/queue/

Upvotes: 2

Related Questions