jQuery Effects - Animation
The jQuery animate() method allows you to create custom animations.
jQuery Animation - animate() Method
The jQuery animate() method is used to create custom animations.
Syntax:
The required params parameter defines the CSS properties that form the animation.
The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.
The optional callback parameter is the name of a function to be executed after the animation completes.
The following example demonstrates a simple application of the animate() method. It moves the <div> element 250 pixels to the right:
Example
$("button").click(function(){
$("div").animate({left:'250px'});
});
| | By default, all HTML elements have a static position and cannot be moved. <br>To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute! | | --- | --- |
jQuery animate() - Manipulating Multiple Properties
Note that you can use multiple properties during the animation:
Example
$("button").click(function(){
$("div").animate({
left:'250px',
opacity:'0.5',
height:'150px',
width:'150px'
});
});
| | Can the animate() method be used to manipulate all CSS properties? <br> <br> Yes, almost all! However, remember that when using animate(), all property names must be written using Camel Case notation. For example, use paddingLeft instead of padding-left, marginRight instead of margin-right, etc. Additionally, color animations are not included in the core jQuery library. If you need to animate colors, you need to download the Color Animation plugin from jquery.com. | | --- | --- |
jQuery animate() - Using Relative Values
You can also define relative values (these values are relative to the element's current value). Prefix the value with += or -=:
Example
$("button").click(function(){
$("div").animate({
left:'250px',
height:'+=150px',
width:'+=150px'
});
});
jQuery animate() - Using Predefined Values
You can even set the animation value of a property to "show", "hide", or "toggle":
Example
$("button").click(function(){
$("div").animate({
height:'toggle'
});
});
jQuery animate() - Using Queue Functionality
By default, jQuery provides queue functionality for animations.
This means that if you write multiple animate() calls one after another, jQuery creates an "internal" queue with these method calls. Then it runs the animate calls one by one.
Example 1
$("button").click(function(){
var div=$("div");
div.animate({height:'300px',opacity:'0.4'},"slow");
div.animate({width:'300px',opacity:'0.8'},"slow");
div.animate({height:'100px',opacity:'0.4'},"slow");
div.animate({width:'100px',opacity:'0.8'},"slow");
});
The following example moves the <div> element 100 pixels to the right and then increases the font size of the text:
Example 2
$("button").click(function(){
var div=$("div");
div.animate({left:'100px'},"slow");
div.animate({fontSize:'3em'},"slow");
});