jQuery fadeToggle() Method


The jQuery fadeToggle() method display or hide the selected elements by animating their opacity in such a way that if the element is initially displayed, it will be fade out; if hidden, it will be fade in (i.e. toggles the fading effect).

Example

<script>
$(document).ready(function(){
    // Toggles paragraphs display with fading
    $(".toggle-btn").click(function(){
        $("p").fadeToggle();
    });
});
</script>

Similarly, you can specify the duration parameter for the fadeToggle() method like fadeIn()/fadeOut() method to control the duration or speed of the fade toggle animation.

Example

<script>
$(document).ready(function(){
    // Fade Toggles paragraphs with different speeds
    $(".toggle-btn").click(function(){
        $("p.normal").fadeToggle();
        $("p.fast").fadeToggle("fast");
        $("p.slow").fadeToggle("slow");
        $("p.very-fast").fadeToggle(50);
        $("p.very-slow").fadeToggle(2000);
    });
});
</script>

Similarly, you can also specify a callback function for the fadeToggle() method.

Example

<script>
$(document).ready(function(){
    // Display alert message after fade toggling paragraphs
    $(".toggle-btn").click(function(){
        $("p").fadeToggle(1000, function(){
            // Code to be executed
            alert("The fade-toggle effect is completed.");
        });
    });
});
</script>

jQuery fadeTo() Method

The jQuery fadeTo() method is similar to the .fadeIn() method, but unlike .fadeIn() the fadeTo() method lets you fade in the elements to a certain opacity level.

$(selector).fadeTo(speed, opacity, callback);

The required opacity parameter specifies the final opacity of the target elements that can be a number between 0 and 1. The duration or speed parameter is also required for this method that specifies the duration of the fade to animation.

Example

<script>
$(document).ready(function(){
    // Fade to paragraphs with different opacity
    $(".to-btn").click(function(){
        $("p.none").fadeTo("fast", 0);
        $("p.partial").fadeTo("slow", 0.5);
        $("p.complete").fadeTo(2000, 1);
    });
});
</script>

Leave a Reply

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