jQuery has 2 fading methods which are .fadeIn() and .fadeOut().
The fadeIn method displays the element by fading it to opaque.
The fadeOut method hides the element by fading it to transparent.
Note – jQuery does the fading by changing the opacity of the element.
$(selector).fadeIn(speed,easing,callback)
$(selector).fadeOut(speed,easing,callback)
Parameter | Description |
---|---|
speed | Optional. Specifies the speed of the fading effect. Possible values:
|
easing | Optional. Default value is “swing”. Specifies the speed of the element at different points of the animation. Possible values:
|
Callback | Optional. A function to be executed after the fadeIn() or fadeOut() methods are completed |
Let us see how to do fadeIn() & fadeOut() on a div element.
<div id="div1">
Hello, I will fade in or fade out
</div>
<button id="button1">Fade Out</button> <button id="button2">Fade In</button>
$("#button1").click(function (e) {
$("#div1").fadeOut();
});
$("#button2").click(function (e) {
$("#div1").fadeIn();
});
When the button1 is clicked then the div1 fades out and becomes hidden (style=”display: none”).
This happens because of .fadeOut() method.
Similarly when button2 is clicked then the div1 element, which is currently hidden due to the clicking of button1, fades in and gets displayed, and this happens due to .fadeIn() method.
Now I will show how to use all the 3 parameters of the .fadeIn() and .fadeOut() methods. These 3 parameters are – Speed, Easing & Callback Function.
<div id="div2">
Hello, I will fade in or fade out
</div>
<button id="button3">Fade Out</button> <button id="button4">Fade In</button>
$("#button3").click(function (e) {
$("#div2").fadeOut(3000, "linear", function () {
alert("fadeOut() finished!");
});
});
$("#button4").click(function (e) {
$("#div2").fadeIn(3000, "linear", function () {
alert("fadeIn() finished!");
});
});
In the above code I have set the speed of fading as 3 seconds, easing to be linear, and a callback function which shows an alert box when the fading completes.
Check the below link: