Animations in jQuery
Get introduced to animations in jQuery and learn about the animate() method.
We'll cover the following
What are animations?
Animations are customizable and user-defined effects. They are used to achieve a functionality that cannot be done with the default jQuery effects.
animate()
method
Animations are achieved in jQuery using the animate()
method. The animate()
method works exactly like an effect, but takes another argument of css parameters. The syntax for the animate()
method is as follows:
$("selector").animate({css_parameters},speed,callback)
Here, speed
and callback
are optional arguments. The css_parameters
are compulsory and adjusted by the user to perform the desired animations.
Example
To better understand animations, check out the simple example shown below. When a div element is clicked, it should:
- Move 75 pixels rightwards
- Move 75 pixels downwards
- Increase its width to 25 pixels
- Increase its font size to 35 pixels
This functionality cannot be achieved with any default jQuery effects. We can only achieve this functionality using the animate()
method with appropriate CSS parameters, shown in lines 3-9.
Using relative values
In the example above, the CSS parameter values are absolute. If we click twice on the div
element, it remains in place because it is already present on the destination specified by the CSS parameters.
What if we want the same animation to take place on all further clicks on the div
element?
We can do this by assigning relative values to CSS parameters and appending +=
or -=
before the parameters. +=
adds the specified value to the current CSS value. Likewise, -=
subtracts the specified value from the current CSS value.
In the example below, we added +=
before all the CSS parameter values. Now, if we click on the div
element more than once, it repeats the same animation relative to its current position.