jQuery fadeIn & fadeOut Methods

jQuery fadeIn & fadeOut Methods

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.

jQuery FadeIn Method Syntax

$(selector).fadeIn(speed,easing,callback)

jQuery FadeOut Method Syntax

$(selector).fadeOut(speed,easing,callback)

Parameter Description
speed Optional.
Specifies the speed of the fading effect.
Possible values:

  • Milliseconds in numbers
  • “slow”
  • “fast”
easing Optional.
Default value is “swing”.
Specifies the speed of the element at different points of the animation.
Possible values:

  • “swing” – slower speed at the beginning & end. Faster in the middle
  • “linear” – constant speed
Callback Optional.
A function to be executed after the fadeIn() or fadeOut() methods are completed

jQuery FadeIn & FadeOut Example

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.

Sometimes we need to select elements in the DOM using their indexes. An example for this would be selecting 3rd children of an element. Here jQuery .eq() method comes out to be very useful.

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.

jQuery FadeIn & FadeOut with “Speed”, “Easing” & “Callback Function”

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 links (DEMO & DOWNLOAD):

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.