Fading
Fade elements in and out by changing their opacity.
Syntax
$(selector).fadeIn(speed); $(selector).fadeTo(speed, opacity);Fade effects animate opacity:
.fadeIn()— fade from invisible to visible..fadeOut()— fade to invisible..fadeToggle()— fade in or out depending on state..fadeTo(speed, opacity)— fade to a specific opacity like 0.5.
Example
Loading editor…
Press Run to see the result.
When to use it
- An image carousel fades one slide out and the next slide in for a smooth crossfade transition.
- A notification bar fades out automatically after three seconds using .fadeOut(3000).
- A lightbox fades the overlay to a specific opacity with .fadeTo() to keep the background partially visible.
More examples
Fade in and fade out buttons
.fadeIn() and .fadeOut() animate opacity from 0 to 1 (and back) over the given milliseconds.
<button id="fi">Fade In</button>
<button id="fo">Fade Out</button>
<div id="box" style="display:none;padding:20px;background:#b3d9ff;">Fading box</div>
<script>
$(function () {
$("#fi").click(function () { $("#box").fadeIn(600); });
$("#fo").click(function () { $("#box").fadeOut(600); });
});
</script>Auto-dismiss notification with fadeOut
A setTimeout delays the fadeOut call so the notification is visible for three seconds before fading away.
<div id="notice" style="padding:12px;background:#4caf50;color:#fff;">Saved successfully!</div>
<script>
$(function () {
setTimeout(function () {
$("#notice").fadeOut(1000);
}, 3000);
});
</script>Fade to partial opacity with fadeTo
.fadeTo(duration, opacity) animates to a specific opacity level rather than fully hiding the element.
<img id="photo" src="hero.jpg" alt="Hero" style="width:200px;" />
<button id="dim">Dim image</button>
<button id="restore">Restore</button>
<script>
$(function () {
$("#dim").click(function () { $("#photo").fadeTo(400, 0.3); });
$("#restore").click(function () { $("#photo").fadeTo(400, 1); });
});
</script>
Discussion