jQuery
In this tutorial we will learn about animation in jQuery.
We use the animate()
method to animate properties of an element.
Syntax
$(selector).animate({
property: value;
});
In the following example we have a div having id "sample-div1" and we are going to increase its height to 100px using the animate()
method.
HTML
<div id="sample-div1">
<p>Hello World</p>
</div>
CSS
#sample-div1 {
border: 1px solid #111;
}
jQuery
$("#sample-div1").animate({
"height": 100
});
We can also set the duration for the animation by passing time in miliiseconds to the animate()
method.
Syntax
$(selector).animate({
property: value;
}, duration);
In the following example we have a div having id "sample-div1" and we are going to increase its height to 20% in 3000 milliseconds using the animate()
method.
HTML
<div id="sample-div1">
<p>Hello World</p>
</div>
CSS
#sample-div1 {
border: 1px solid #111;
}
jQuery
$("#sample-div1").animate({
"height": "20%"
}, 3000);
We can also add function that will be executed after the animation is complete.
Syntax
$(selector).animate({
property: value;
}, duration, complete);
In the following example we have a div having id "sample-div1" and we are increasing its height to 200px in 3000 milliseconds using animate()
method. After the animation completes we are going to return the height of the div using the css()
method.
HTML
<div id="sample-div1">
<p>Hello World</p>
</div>
CSS
#sample-div1 {
border: 1px solid #111;
}
jQuery
$("#sample-div1").animate({
"height": 200
}, 3000, function() {
console.log("Height: " + $(this).css("height")); //this will print "Height: 200"
});
The $(this)
refers to the element that we are animating.
An easing function specifies the speed at which the animation progresses at different points within the animation. And by default the value is swing
. jQuery provides two values for easing and the two values are swing
and linear
. The linear value easing progresses at a contant pace.
Syntax
$(selector).animate({
property: value;
}, duration, easing, complete);
In the following example we are changing the height of the div having id "sample-div1" to 200px in 1000 milliseconds. We are using the linear
ease and when the animation completes we are printing "Done!" in the browser console.
$("#sample-div1").animate({
"height": "200px"
}, 1000, "linear", function(){
console.log("Done!");
});
ADVERTISEMENT