Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I animate multiple elements sequentially using jQuery?

I thought it would be simple but I still can't get it to work. By clicking one button, I want several animations to happen - one after the other - but now all the animations are happening at once. Here's my code - can someone please tell me where I'm going wrong?:

$(".button").click(function(){   $("#header").animate({top: "-50"}, "slow")   $("#something").animate({height: "hide"}, "slow")   $("ul#menu").animate({top: "20", left: "0"}, "slow")   $(".trigger").animate({height: "show", top: "110", left: "0"}, "slow"); }); 
like image 718
lnvrt Avatar asked Aug 02 '09 04:08

lnvrt


People also ask

How can use a animate () method in jQuery?

The animate() is an inbuilt method in jQuery which is used to change the state of the element with CSS style. This method can also be used to change the CSS property to create the animated effect for the selected element. Syntax: (selector).

Can the jQuery animate () method be used to animate any CSS property?

The animate() method is typically used to animate numeric CSS properties, for example, width , height , margin , padding , opacity , top , left , etc. but the non-numeric properties such as color or background-color cannot be animated using the basic jQuery functionality. Note: Not all CSS properties are animatable.

Which method is available in jQuery for animation?

The animate() method performs a custom animation of a set of CSS properties. This method changes an element from one state to another with CSS styles. The CSS property value is changed gradually, to create an animated effect.

What is the default easing used for jQuery animation?

An easing function specifies the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing , and one that progresses at a constant pace, called linear .


1 Answers

Queue only works if your animating the same element. Lord knows why the above got voted up but it will not work.

You will need to use the animation callback. You can pass in a function as the last param to the animate function and it will get called after the animation has completed. However if you have multiple nested animations with callbacks the script will get pretty unreadable.

I suggest the following plugin which re-writes the native jQuery animate function and allows you to specify a queue name. All animations that you add with the same queue name will be run sequentially as demonstrated here.

Example script

  $("#1").animate({marginTop: "100px"}, {duration: 100, queue: "global"});   $("#2").animate({marginTop: "100px"}, {duration: 100, queue: "global"});   $("#3").animate({marginTop: "100px"}, {duration: 100, queue: "global"}); 
like image 135
redsquare Avatar answered Sep 18 '22 23:09

redsquare