How to do Animation with jQuery

You can use jQuery to create animations on the fly. Here's how.

jQuery includes the animate() method that allows you to create an animation.

More specifically, the animate() method enables you to perform a custom animation on a set of numeric CSS properties.

The animate() method accepts many parameters but the only required parameter is the object of CSS properties.

Here's a small snippet of sample code to demonstrate how to call the animate() method:

Here's a working example:

Note that the font size uses an absolute value (3em) while the letter spacing uses a relative value (+=0.3em). If you replay the animation, you'll notice that the letter spacing increases with each re-run but the font size remains at the same size that it was after the first run.

This happens because relative values will add the amount on to the existing amount, whereas, absolute values don't. Therefore, the element reaches its absolute value the first time the animation is run. Any subsequent replays will have no affect on that particular property.

Animating Non-Numeric Properties

Generally, jQuery animations only work on properties with numeric values. To animate non-numeric properties you'll need to use a plugin. For example, to animate a color property (such as background-color) you'll need to use the jQuery Color plugin.

However, jQuery does also have the show, hide, and toggle keywords that you can use instead of a numeric value. More on these keywords below.

Also, depending on what you're trying to achieve, you can always use straight CSS animations.

The show, hide, and toggle Keywords

In addition to numeric values, each property accepts show, hide, and toggle as a value.

Here's an example of using toggle() as a value:

Chained Animations

You can also create chained animations — multiple animations that run, one after the other.

To do this, simply use multiple animate() properties, one after the other. Like this:

Working example: