jQuery Fading Effects


In this tutorial you will learn how to fade in and out elements using jQuery.

jQuery fadeIn() and fadeOut() Methods

You can use the jQuery fadeIn() and fadeOut() methods to display or hide the HTML elements by gradually increasing or decreasing their opacity.

Example

<script>
$(document).ready(function(){
    // Fading out displayed paragraphs
    $(".out-btn").click(function(){
        $("p").fadeOut();
    });
    
    // Fading in hidden paragraphs
    $(".in-btn").click(function(){
        $("p").fadeIn();
    });
});
</script>

Like other jQuery effects methods, you can optionally specify the duration or speed parameter for the fadeIn() and fadeOut() methods to control how long the fading animation will run. Durations can be specified either using one of the predefined string 'slow' or 'fast', or in a number of milliseconds; higher values indicate slower animations.

Example

<script>
$(document).ready(function(){
    // Fading out displayed paragraphs with different speeds
    $(".out-btn").click(function(){
        $("p.normal").fadeOut();
        $("p.fast").fadeOut("fast");
        $("p.slow").fadeOut("slow");
        $("p.very-fast").fadeOut(50);
        $("p.very-slow").fadeOut(2000);
    });
    
    // Fading in hidden paragraphs with different speeds
    $(".in-btn").click(function(){
        $("p.normal").fadeIn();
        $("p.fast").fadeIn("fast");
        $("p.slow").fadeIn("slow");
        $("p.very-fast").fadeIn(50);
        $("p.very-slow").fadeIn(2000);
    });
});
</script>

Note: The effect of fadeIn()/fadeOut() method looks similar to show()/hide(), but unlike show()/hide() method the fadeIn()/fadeOut() method only animates the opacity of the target elements and does not animates their dimensions.

You can also specify a callback function to be executed after the fadeIn() or fadeOut() method completes. We’ll learn more about the callback function in upcoming chapters.

Example

<script>
$(document).ready(function(){
    // Display alert message after fading out paragraphs
    $(".out-btn").click(function(){
        $("p").fadeOut("slow", function(){
            // Code to be executed
            alert("The fade-out effect is completed.");
        });
    });
    
    // Display alert message after fading in paragraphs
    $(".in-btn").click(function(){
        $("p").fadeIn("slow", function(){
            // Code to be executed
            alert("The fade-in effect is completed.");
        });
    });
});
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *