Episode 19 of 24
Animation in jQuery
Learn to create custom animations with jQuery animate() method.
jQuery's .animate() method lets you create custom animations by gradually changing CSS properties.
Basic Animation
$(".box").animate({
width: "300px",
height: "200px",
opacity: 0.5
}, 1000); // Duration in milliseconds
Animation with Easing
// "swing" (default) and "linear" are built-in
$(".box").animate({
left: "500px"
}, 1000, "swing");
$(".box").animate({
left: "500px"
}, 1000, "linear");
Callback Function
$(".box").animate({
opacity: 0,
marginTop: "50px"
}, 800, function() {
// Runs after animation completes
$(this).remove();
console.log("Animation done!");
});
Sequential Animations (Queuing)
// Animations queue by default
$(".box")
.animate({ left: "300px" }, 500)
.animate({ top: "200px" }, 500)
.animate({ opacity: 0.5 }, 500)
.animate({ opacity: 1 }, 500);
Relative Values
// Use += and -= for relative changes
$(".box").animate({
left: "+=50px", // Move 50px to the right
top: "-=20px", // Move 20px up
fontSize: "+=4px" // Increase font size by 4px
}, 400);
stop() — Stop Animations
// Stop current animation
$(".box").stop();
// Stop and clear the animation queue
$(".box").stop(true);
// Stop, clear queue, and jump to end
$(".box").stop(true, true);
Practical Example
// Animated notification
function showNotification(message) {
$("<div>")
.addClass("notification")
.text(message)
.appendTo("body")
.css({ right: "-300px", opacity: 0 })
.animate({ right: "20px", opacity: 1 }, 400)
.delay(3000)
.animate({ right: "-300px", opacity: 0 }, 400, function() {
$(this).remove();
});
}