We can use jQuery to fade in an element using the jQuery fadeIn() method. The jQuery fadeIn() method will change the opacity of an element to 1 at a speed that we can set.
$("#div1").fadeIn(1000);
In the code above, the number “1000” is the number of milliseconds you want the fade in to happen by, which in this case is 1000 milliseconds or 1 second.
If you leave the fadeIn() method empty it will have the default time of 400 milliseconds.
$("#div1").fadeIn();
Let’s say we have the following HTML:
This is some div
Right now #div1 is not being displayed. If we wanted to change the opacity of #div1 to 1 and show it, we can use the jQuery fadeIn() method in the following JavaScript code.
$("#div1").fadeIn();
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#div1").fadeIn();
Note that we could also do this by using the jQuery fadeTo() method.
$("#div1").fadeTo(1000,1);
Using the jQuery fadeIn Method to Show 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 show it. We will also provide a button to hide the div so that the user can fade in and fade out as many times as they want.
Fade In
Fade Out
We can utilize both the jQuery click() method and jQuery fadeIn() method to show the div.
We will also use the jQuery fadeOut() method to let the user hide 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").fadeIn(2000);
});
$("#click-me2").click(function(){
$("#div2").fadeOut(2000);
});
The final code and output for this example of using the jQuery fadeIn method to show a div is below:
Code Output:
Full Code:
Fade In
Fade Out
<script>
$("#click-me1").click(function(){
$("#div2").fadeIn(2000);
});
$("#click-me2").click(function(){
$("#div2").fadeOut(2000);
});
</script>
Hopefully this article has been useful for you to understand how to use the jQuery fadeIn method.