Fading Effects
In this page:
fadeIn()
fadeIn() reveals a hidden element by animating its opacity from 0 up to 1 over a chosen duration. It only affects transparency, so the element's size and position stay fixed throughout the animation.
Example: fadeIn()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box" style="display:none">Fading in</div>
<script>
$("#box").fadeIn(1000);
</script>
</body>
</html>
fadeOut()
fadeOut() runs the opposite animation, gradually reducing an element's opacity down to 0 and then setting display:none once the fade completes, removing it from layout. Because the element is set to display:none afterward, it's completely removed from the page's layout flow, not just invisible.
Example: fadeOut()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">Fading out</div>
<script>
$("#box").fadeOut(1000);
</script>
</body>
</html>
fadeToggle()
fadeToggle() checks whether an element is currently visible or faded out and animates it to the opposite state, giving you a single call that works for both directions. This is a convenient shortcut when you don't want to track an element's current visibility state yourself before deciding which method to call.
Example: fadeToggle()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">Toggle fade</div>
<button id="btn">Fade</button>
<script>
$("#btn").on("click", function() {
$("#box").fadeToggle();
});
</script>
</body>
</html>
fadeTo()
fadeTo() animates an element to a specific opacity value you choose, like 0.5, rather than always going fully to 0 or 1 -- useful for a dimmed or semi-transparent effect. This gives you finer control than a simple fade in or out, useful for creating a dimmed overlay or a subtle hover effect.
Example: fadeTo()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">Dimmed content</div>
<script>
$("#box").fadeTo(1000, 0.5);
</script>
</body>
</html>
Fade Speed
Every fading method accepts a duration argument -- either milliseconds or a keyword like slow or fast -- controlling how long the opacity transition takes to complete. You can also pass a callback function as a second argument, which runs automatically once the fade animation finishes.
Example: Fade Speed
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">Content</div>
<script>
$("#box").fadeOut("slow", function() {
console.log("Fade complete");
});
</script>
</body>
</html>
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: