We can use jQuery to fade out an element using the jQuery fadeOut() method. The jQuery fadeOut() method will change the opacity of an element to 0 and remove it from the HTML changing its CSS display property to “display: none”.

$("#div1").fadeOut(1000);

In the code above, the number “1000” is the number of milliseconds you want the fade out to happen by, which in this case is 1000 milliseconds or 1 second.

If you leave the fadeOut() method empty it will have the default time of 400 milliseconds.

$("#div1").fadeOut();

Let’s say we have the following HTML:

This is some div

If we wanted to change the opacity of #div1 to 0 and hide it, we can use the jQuery fadeOut() method in the following jQuery code.

$("#div1").fadeOut();

If you are using WordPress, don’t forget to change the $ to jQuery as below:

jQuery("#div1").fadeOut();

Note that we could also do this by using the jQuery fadeTo() method. The main difference being that the fadeTo() method will change the opacity to 0, which means it won’t be visible but will still take up space. While the fadeOut() method will remove the div and it will not take up any space.

$("#div1").fadeTo(1000,0);

Using the jQuery fadeOut Method to Hide a Div with a Click

In this simple example, we will have a div with a greenish background. We will provide a button for the user to use to change the div’s opacity and hide it. We will also provide a button to show the div so that the user can fade in and fade out as many times as they want.


Fade Out
Fade In

We can utilize both the jQuery click() method and jQuery fadeOut() method to hide the div.

We will also use the jQuery fadeIn() method to let the user show the div.

We will give both fadeIn() and fadeOut() methods the parameter 2000, which means it will display or hide the div in 2000 milliseconds(2 seconds).

Here is the JavaScript code below:

$("#click-me1").click(function(){
  $("#div2").fadeOut(2000);
});

$("#click-me2").click(function(){
  $("#div2").fadeIn(2000);
});

The final code and output for this example of using the jQuery fadeOut method to hide a div is below:

Code Output:

Fade Out
Fade In

Full Code:


Fade Out
Fade In
<script> $("#click-me1").click(function(){ $("#div2").fadeOut(2000); }); $("#click-me2").click(function(){ $("#div2").fadeIn(2000); }); </script>

Hopefully this article has been useful for you to understand how to use the jQuery fadeOut method.

Categorized in:

jQuery,

Last Update: February 26, 2024