The animate() method in jQuery allows you to create custom animations by gradually changing CSS properties over time.
The basic syntax of animate() includes CSS properties, duration, and an optional callback.
// Basic animate syntax
$("#box").animate({ width: "300px", opacity: 0.5 }, 1000);
// Animate multiple CSS properties
$("#animateBox").animate({
left:"250px",
opacity:0.5,
height:"100px",
width:"300px"
},1000);
// Reset animation state
$("#animateBox").animate({
left:"0px",
opacity:1,
height:"50px",
width:"150px"
},1000);
You can stack multiple animate() calls to create a sequence. jQuery will put them in an internal "queue" and run them one after another.
// Chaining multiple animations with a callback
$("#runChain").click(function() {
$("#chainBox")
.animate({ left: "100px" }, 500)
.animate({ top: "50px" }, 500)
.animate({ left: "0px" }, 500)
.animate({ top: "0px" }, 500, function() {
$("#statusUpdate").text("Sequence Finished!");
});
});
The box smoothly moves horizontally, resizes, and changes opacity. Reset brings it back to its original state.
Callbacks execute after the animation completes.
// Callback runs after animation completes
$("#animateBox").animate({ left:"250px" },1000,function(){
alert("Animation done!");
});
position when animating left or top