What are the toggle method in JQuery with example?

Asked 27-Jul-2021
Viewed 155 times

1 Answer


1

 JQuery toggle () is a special kind of method used to show or hide an element, but this function can only be done from a function.
If the element is visible it hides it, if it is hidden it shows it.
Syntax:

$(selector).toggle ();
$(selector).toggle (speed, callback);
$(selector).toggle (display);
Speed and callback is an optional parameter. Speed specifies the delay of showing elements these possible vales are 'slow', 'fast' and milliseconds. Callback function to be called after completion of show () or hide (). We also put true and false value for showing and hiding element respectively.
<!DOCTYPE html>

<html lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta charset='utf-8' />
    <title></title>
    <style>
        button {
            width:100px;
            height:30px;
        }
    </style>
    <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
<script>
    $(document).ready(function () {
        $('.show').click(function () {
            $('img').toggle(500);
            if ($(this).text() == 'Show Image') {
                $(this).text('Hide Image');
            }else{
                $(this).text('Show Image');
            }
        });
    });
</script>
</head>
<body>
    <img src='https://source.unsplash.com/1600x900/?nature,water' id='image' width='500px' height='auto'/></br></br>
    <button class='show'>Hide Image</button>
</body>
</html>

What are the toggle method in JQuery with example?