jQuery Animation

Animating CSS Properties with jQuery

The jQuery animation function typically takes three parameters.

Properties

The first is a map of properties that you would like to animate. The property can be anything that is a number. For more details about which properties can be animated, see the documentation.

Duration

The second parameter is the number of milliseconds that the animation should take place over.

Easing

The last parameter is the transition curve. There are two easing functions always available, "linear" and "swing". Other easing functions are available through the optionally installed User Interface Suite.

Example:

$("#myBox").animate({left:-500,opacity:0},800,"swing");

This tells jQuery to slide a box with id="myBox" left 500px while at the same time dropping the opacity down to zero. This should be done over 800 milliseconds using the easing function swing.

It is also possible to call another function after the animation completes by adding a fourth parameter to the animate function call. Ex:

$("#myBox").animate({left:-500,opacity:0},800,"swing",function(){
	//now do this;
});

Step-by-Step Instructions

  1. Add jQuery to your webpage.
  2. Add an element to your page that you would like animated. It should be an item that can move (i.e. position: relative or position:absolute)
  3. At the animation code to an action. For example, my action here is clicking the [Animate Now] button. It can be any event; say when a page loads, when something is moused over, or on a mouse click, or touch, etc.
  4. In this example, the bird’s HTML is: <div id="bird"><img src="animatedBird.png" width="198" height="313"></div>
  5. The CSS for the #bird div is: position:relative; left:400px; width:198px;
  6. The code on the button is:
var position = false;
$('#trigger').on('click', function(e) {
	if (position) {
		$('#bird').animate({left:800}, 4000, "swing");
		position = false;
	} else {
		$('#bird').animate({left:00}, 200, "linear");
		position = true;
	}
}); 

 


Note: It is also possible to do some native CSS animation, but jQuery has more power.