jQuery animate method
The .animate()
method in jQuery allows you to create custom animations by changing CSS properties of elements over a specified duration. This method provides more control compared to jQuery's built-in animation methods like .fadeIn()
, .slideUp()
, etc.
Basic Syntax
$(selector).animate({ properties }, duration, easing, callback);
selector
: The element(s) you want to animate.properties
: An object containing the CSS properties you want to animate and their target values.duration
: The time (in milliseconds) that the animation should take. You can also use keywords like"slow"
(600ms) or"fast"
(200ms).easing
: (Optional) Specifies the speed of the animation over time. Common values are"swing"
(default) and"linear"
.callback
: (Optional) A function to execute after the animation completes.
Example 1: Simple Animation
Here's an example of a basic animation that changes the width of a div
:
$("div").animate({
width: "300px",
opacity: 0.5
}, 1000);
In this example:
- The
div
's width will animate to300px
. - The
opacity
will animate to0.5
. - The animation will take 1000 milliseconds (1 second).
Example 2: Multiple Animations
You can chain multiple animations by calling .animate()
successively:
$("div").animate({
width: "300px"
}, 1000).animate({
height: "300px"
}, 1000).animate({
opacity: 0.5
}, 1000);
This code will:
- Animate the width to
300px
over 1 second. - Then, animate the height to
300px
over 1 second. - Finally, animate the opacity to
0.5
over 1 second.
Example 3: Using Easing and Callback
Here’s an example that uses a custom easing function and a callback:
$("div").animate({
left: "200px"
}, 1500, "linear", function() {
alert("Animation complete!");
});
In this example:
- The
div
will move200px
to the right over 1.5 seconds. - The animation will have a linear easing, meaning it will move at a constant speed.
- Once the animation is complete, an alert box will display.
Animatable Properties
Not all CSS properties can be animated with .animate()
. Common animatable properties include:
- Numeric values (e.g.,
width
,height
,opacity
,margin
,padding
,top
,left
,bottom
,right
). - Colors (e.g.,
backgroundColor
,color
) when using jQuery UI or a similar plugin.
Example 4: Animating Colors
If you include jQuery UI, you can also animate colors:
$("div").animate({
backgroundColor: "#ff0000"
}, 1000);
In this example, the background color of the div
will transition to red over 1 second.
Example 5: Relative Animations
You can use +=
or -=
to animate properties relative to their current value:
$("div").animate({
left: "+=50px"
}, 500);
This will move the div
50px to the right from its current position over 0.5 seconds.