jQuery Fade
Fading is a smoother, more elegant way to reveal and conceal content. Instead of an element blinking in or out, its opacity glides from invisible to fully solid or back again. jQuery ships four fade methods: fadeIn(), fadeOut(), fadeToggle(), and fadeTo(). In this lesson you will see how each one behaves and when to reach for it.
Fading elements in and out
fadeIn() gradually raises the opacity of a hidden element until it is fully visible, while fadeOut() lowers the opacity to zero and then sets display to none. Unlike show() and hide(), which can animate size and position, the fade methods only change transparency, which gives a soft, professional feel that works well for tooltips, alerts, and image galleries.
fadeIn() and fadeOut()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="showBtn">Show</button>
<button id="hideBtn">Hide</button>
<div id="box" style="display:none; width:100px; height:100px; background-color:tomato;"></div>
<script>
$("#showBtn").click(function() {
$("#box").fadeIn("slow");
});
$("#hideBtn").click(function() {
$("#box").fadeOut(1000);
});
</script>
</body>
</html>Just like the hide/show methods, every fade method accepts an optional speed and a callback. The speed controls how long the transition lasts, and the callback fires once the fade has completed. This makes it easy to run follow-up code, such as removing an element only after it has fully faded away.
fadeToggle() and fadeTo()
fadeToggle() combines fadeIn() and fadeOut() into one method: if the element is visible it fades out, and if it is hidden it fades in. fadeTo() is the odd one out. It fades an element to a specific opacity level between 0 and 1 that you provide, and it does not hide the element afterwards, so you can leave something semi-transparent on purpose.
fadeToggle() and fadeTo()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="toggleBtn">Toggle Panel</button>
<div id="panel">Panel content</div>
<button id="dimBtn">Dim Overlay</button>
<div id="overlay" style="width:100px; height:100px; background-color:navy;"></div>
<script>
$("#toggleBtn").click(function() {
$("#panel").fadeToggle(400);
});
// Fade to 50% opacity over 600ms
$("#dimBtn").click(function() {
$("#overlay").fadeTo(600, 0.5);
});
</script>
</body>
</html>- fadeIn() animates from transparent to fully visible.
- fadeOut() animates to transparent, then applies display:none.
- fadeToggle() switches between faded in and faded out.
- fadeTo() fades to a chosen opacity and stops there.
- The opacity value in fadeTo() must be between 0 (invisible) and 1 (solid).
Exercise: jQuery Fade
Which visual property do jQuery's fade effects primarily animate?