jQuery .animate() Method
The .animate() method in jQuery is a powerful tool that allows you to create custom animations by changing CSS properties over time. Unlike simpler methods like .fadeIn(), .fadeOut(), or .slideToggle(), .animate() gives you full control over the properties and animation behavior.
Syntax
$(selector).animate(properties, duration, easing, complete);
properties: A map of CSS properties to animate, along with their target values.duration: (Optional) The length of the animation in milliseconds or predefined strings ("slow","fast").easing: (Optional) The easing function to use for the transition. The default is"swing". Another option is"linear".complete: (Optional) A callback function to execute after the animation is complete.
Example: Basic Animation
$("button").click(function() {
$("#myDiv").animate({ height: "toggle" });
});
In this example, clicking the button toggles the height of #myDiv.
Example: Animating Multiple Properties
$("button").click(function() {
$("#myDiv").animate({
width: "300px",
height: "300px",
opacity: 0.5
}, 1000);
});
This example animates the width, height, and opacity of #myDiv over 1 second.
Example: Using Easing Functions
$("button").click(function() {
$("#myDiv").animate({
left: "250px"
}, 1000, "linear");
});
This example moves #myDiv to the right by 250 pixels using a linear easing function.
Example: Callback Function
$("button").click(function() {
$("#myDiv").animate({
height: "300px"
}, 1000, function() {
alert("Animation complete!");
});
});
This example shows an alert message after the animation completes.
Custom Animation Properties
- Relative Values: You can use
+=or-=to increase or decrease the current value.$("#myDiv").animate({ left: "+=50px" }); - Queueing Animations: You can chain multiple
.animate()calls to queue animations.