Episode 20 of 24
Fading Elements In and Out
Learn jQuery fade effects — fadeIn, fadeOut, fadeToggle, and fadeTo.
jQuery provides simple methods to fade elements in and out with smooth opacity transitions.
fadeIn()
// Fade in a hidden element
$(".box").fadeIn(); // Default speed
$(".box").fadeIn("slow"); // Slow
$(".box").fadeIn("fast"); // Fast
$(".box").fadeIn(1000); // 1 second
// With callback
$(".box").fadeIn(500, function() {
console.log("Fade in complete!");
});
fadeOut()
$(".box").fadeOut(); // Default speed
$(".box").fadeOut(800); // 800ms
$(".box").fadeOut(400, function() {
$(this).remove(); // Remove after fading out
});
fadeToggle()
// Fades out if visible, fades in if hidden
$("button").click(function() {
$(".content").fadeToggle(400);
});
fadeTo()
Fade to a specific opacity level:
$(".box").fadeTo(400, 0.5); // Fade to 50% opacity
$(".box").fadeTo(400, 1); // Fade back to fully visible
$(".box").fadeTo(400, 0.2); // Fade to 20%
Practical Examples
// Image gallery with fade effect
$(".thumbnail").click(function() {
let src = $(this).attr("src");
$(".main-image").fadeOut(200, function() {
$(this).attr("src", src).fadeIn(200);
});
});
// Notification that fades out
function notify(message) {
let $msg = $("<div class='alert'>").text(message);
$("body").append($msg);
$msg.fadeIn(300).delay(2000).fadeOut(500, function() {
$(this).remove();
});
}
// Sequential fade-in of list items
$("li").hide().each(function(index) {
$(this).delay(index * 150).fadeIn(400);
});