jQuery’s .animate() function has helped many front end developers around the world to create web pages with custom animations and effects by just using combinations of jQuery , css and sometimes images. It helped us get rid of flash for most of the simple (and at times complex) animations. And I must say that this is one of the most important API in jQuery.
The syntax for jQuery’s .animate() function is written as below:
.animate( properties [, duration] [, easing] [, complete] )
properties refer to the CSS properties that you want the element to animate to.
duration is the time value determining how long the animation will last. It accepts string value such as “fast”, “slow” and also numerical values for milliseconds like ‘5000’ etc. This is an optional parameter.
easing refers to the effect that should be used during transition. This is an optional parameter and requires easing plugin.
complete refers to the function that should be called once the animation is over. This too is an optional parameter.
While using .animate() function, it is very important to be clear with the css changes that you want the targeted element to go through during the animation.
The .animate() function basically just alters the css of the targeted element at the speed you mention using the easing option you provided(if any)
So let’s try to understand jQuery .animate() function using examples.
Firstly, let us think of an example. Let us try to animate a simple Div which looks like this :
The CSS for the Div1 is as given below :
border: 2px solid #BBBBBB;
Now let us animate Div1. During the animation process let us increase the height and width of the div to 200px respectively.
We will call the animate function on the click of a button with class “myButton”. The jQuery Code for the same would be :
/*this line in jQuery ensures that the functions wrapped within this gets executed
only when the DOM has loaded. */
<input type="button" class="myButton" value="Click Me"/>
Similarly, you can animate the text too by changing the text size etc using css. You can find many creative animations which were developed using jQuery’s .animate() API. But the basic concept of the animate function revolves around altering the css of the targeted element at the speed you mention using the easing option you provided(if any).
So go ahead and create few creative animations using jQuery’s animate function and don’t forget to share it with us. Happy Coding !