jQuery’s Animate Method

Est. Reading Time: 2 minute

The jQuery library has a collection of methods built for animating and manipulating the DOM.  These effects implement styling changes to produce transitions like fading or element movement.  The full list of methods are available on the jQuery website.

jQuery also contains a nifty method, animate.  Animate allows you to make a timed transition from one style to another.  This comes is handy when other effects methods don’t quite behave or lack needed functionality.

Consider the two snippets:

1: $(‘h1′).fadeOut(1000); 2: $(‘h1′).animate({opacity:’-=1′},1000);

Both perform the same transition, and in one second, the selected element transitions to being transparent.  However, the fadeOut method has a feature that sets the element’s display attribute to none when opacity reaches zero.  This especially becomes an issue if you need the element that fades out to maintain its structure in a template.

The animate method is also capable of manipulating multiple styles in one method.  If we needed to make an element slide on the page while coming into view from being transparent, this can also be done with a single line, separating multiple style changes by a comma.

$(‘h1′).animate({opacity:’+=1′,marginLeft:’+=15px’  },1000);

Relatively and absolutely positioned elements can make use of the left/top CSS styles, but should be used to what works within your template and layout.

Animate and jQuery effect method’s all support callback functions which makes movement order easy.  The snippet below will result in the same animation, but the left margins are not animated until the transparency becomes fully visible.  These can be nested within one another to avoid using setTimeout and setInterval coding.

$(‘h1′).animate({opacity:’+=1′},1000,function(){ $(this).animate({marginLeft:’+=15px’},1000); });