How to Fade Out an Element Using jQuery
In web development, dynamically hiding elements with smooth
transitions enhances the overall user experience. This article explains
how to use jQuery's built-in .fadeOut() method to
transition an element from visible to hidden by animating its opacity.
You will learn the correct syntax, understand the available parameters
such as duration and callback functions, and see practical code examples
demonstrating its implementation.
The .fadeOut() Method
The primary jQuery method used to fade an element out of visibility
is .fadeOut(). This method animates the opacity of the
matched elements. Once the opacity reaches 0, the
display style property is automatically set to
none, ensuring the element no longer affects the layout of
the page.
Basic Syntax
$(selector).fadeOut(duration, easing, complete);Parameters
duration(optional): A string or number determining how long the animation will run. Common string values are"slow"(600 milliseconds) and"fast"(200 milliseconds). You can also provide a number in milliseconds (e.g.,1000for 1 second). The default value is400milliseconds.easing(optional): A string indicating which easing function to use for the transition. jQuery provides"swing"(default) and"linear".complete(optional): A callback function that executes once the fade-out animation is entirely finished for each matched element.
Code Examples
1. Basic Fade Out
To hide an element with the ID target using the default
speed:
$("#target").fadeOut();2. Custom Duration
To hide an element over the course of 1.5 seconds (1500 milliseconds):
$(".box").fadeOut(1500);3. Using a Callback Function
If you need to execute code after the element has completely disappeared—such as removing it from the DOM—you can pass a callback function:
$("#notification").fadeOut("slow", function() {
$(this).remove();
});Related Fading Methods
jQuery also provides related methods for other fading effects:
.fadeIn(): Fades an element into visibility by changing its opacity from 0 to 1 and settingdisplayto its default state..fadeToggle(): Toggles between.fadeIn()and.fadeOut()depending on the element's current visibility..fadeTo(): Fades an element's opacity to a specific target value without settingdisplay: none.