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 in different points of the animation.
Possible values:

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

jQuery FadeIn & FadeOut Example

Let us show you 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 (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.

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 ‘speed’ of fading as 3 seconds, easing to be ‘linear’ and a ‘callback function’ which shows alert box when the fading completes.

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 “WordPress, SEO, jQuery, HTML” and more.