jQuery fadeToggle() example

The jQuery fadeToggle() method toggles between the fadeIn() and fadeOut() methods.
If the elements are faded out, fadeToggle() will fade them in.
If the elements are faded in, fadeToggle() will fade them out.

Syntax

$(selector).fadeToggle(speed,callback);
  • The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.
  • The optional callback parameter is a function to be executed after the fading completes.

Example 1

The following example demonstrates the fadeToggle() method with different parameters:
<!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                $("#div1").fadeToggle();
                $("#div2").fadeToggle("slow");
                $("#div3").fadeToggle(3000);
            });
        });
    </script>
</head>

<body>

    <p>Demonstrate fadeToggle() with different speed parameters.</p>

    <button>Click to fade in/out boxes</button><br><br>

    <div id="div1" style="width:80px;height:80px;background-color:red;"></div>
    <br>
    <div id="div2" style="width:80px;height:80px;background-color:green;"></div>
    <br>
    <div id="div3" style="width:80px;height:80px;background-color:blue;"></div>

</body>

</html>
Try it Yourself - Copy paste code in Online HTML Editor to see the result

Example 2

Fades first paragraph in or out, completing the animation within 600 milliseconds and using a linear easing. Fades last paragraph in or out for 200 milliseconds, inserting a "finished" message upon completion.
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>fadeToggle demo</title>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>

<body>

    <button>fadeToggle p1</button>
    <button>fadeToggle p2</button>
    <p>This paragraph has a slow, linear fade.</p>
    <p>This paragraph has a fast animation.</p>
    <div id="log"></div>

    <script>
        $("button").first().click(function() {
            $("p").first().fadeToggle("slow", "linear");
        });
        $("button").last().click(function() {
            $("p").last().fadeToggle("fast", function() {
                $("#log").append("<div>finished</div>");
            });
        });
    </script>

</body>

</html>
Try it Yourself - Copy paste code in Online HTML Editor to see the result

References

Comments