jQuery toggle() function examples

The jQuery toggle() function is a special type of method which is used to toggle between the hide() and show() method. It shows the hidden elements and hides the shown element.

Syntax

$(selector).toggle();  
$(selector).toggle(speed, callback);  
$(selector).toggle(speed, easing, callback);  
$(selector).toggle(display);  
  • speed: It is an optional parameter. It specifies the speed of the delay. Its possible values are slow, fast and milliseconds.
  • easing: It specifies the easing function to be used for transition.
  • callback: It is also an optional parameter. It specifies the function to be called after completion of the toggle() effect.
  • display: If true, it displays element. If false, it hides the element.

Example 1

<!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() {
                $("p").toggle();
            });
        });
    </script>
</head>

<body>

    <button>Toggle between hiding and showing the paragraphs</button>

    <p>This is a paragraph with little content.</p>
    <p>This is another small paragraph.</p>

</body>

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

Example 2 - Toggles all paragraphs

<!doctype html>
<html lang="en">

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

<body>

    <button>Toggle</button>
    <p>Hello</p>
    <p style="display: none">Good Bye</p>

    <script>
        $("button").click(function() {
            $("p").toggle();
        });
    </script>

</body>

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

References


Comments