jQuery fadeTo() example

The jQuery fadeTo() method allows fading to a given opacity (value between 0 and 1).

Syntax

$(selector).fadeTo(speed,opacity,callback);
  • The required speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.
  • The required opacity parameter in the fadeTo() method specifies fading to a given opacity (value between 0 and 1).
  • The optional callback parameter is a function to be executed after the function completes.

Example 1

The following example demonstrates the fadeTo() 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").fadeTo("slow", 0.15);
                $("#div2").fadeTo("slow", 0.45);
                $("#div3").fadeTo("slow", 0.75);
            });
        });
    </script>
</head>

<body>

    <p>Demonstrate fadeTo() with different parameters.</p>

    <button>Click to fade 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

Fade div to a random opacity on each click, completing the animation within 200 milliseconds.
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>fadeTo demo</title>
    <style>
        p {
            width: 80px;
            margin: 0;
            padding: 5px;
        }

        div {
            width: 40px;
            height: 40px;
            position: absolute;
        }

        #one {
            top: 0;
            left: 0;
            background: #f00;
        }

        #two {
            top: 20px;
            left: 20px;
            background: #0f0;
        }

        #three {
            top: 40px;
            left: 40px;
            background: #00f;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>

<body>

    <p>And this is the library that John built...</p>

    <div id="one"></div>
    <div id="two"></div>
    <div id="three"></div>

    <script>
        $("div").click(function() {
            $(this).fadeTo("fast", Math.random());
        });
    </script>

</body>

</html>

References

Comments