Describe jQuery toggle() method in detail with example

The toggle() method is used to toggle between show and hide for selected HTML elements. If elements are hidden then toggle method will show the hidden selected elements and vice versa.

Syntax of toggle jQuery

Following is the syntax of $.toggle method:
$(selector).toggle(speed,callback)
Where
Selector = can be an element like div, p, etc.
Speed = Optional parameter that specifies the hidden speed with possible values of
“slow”
“fast”
Or value in milliseconds
Callback = after jQuery toggle() method is completed, an optional callback function to perform certain action can be given.

Example of $.toggle() method

This example shows how to use jQuery toggle method to hide/show elements. In this example, we will use the toggle method to show/hide DIV with class name “text”. Click on the button to toggle between show and hide states. See it online by the link given below:

<!DOCTYPE html>
<head>
<title>jQuery Testing</title>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
   <script type="text/javascript" language="javascript">
   $(document).ready(function() {
     $(".hidetext").click(function () {
     $(".text").toggle("slow")
  });
  });
   </script>
</head>
<body>
   <button class="hidetext">Toggle yellow line</button>
   <div class="text" style="background-color:yellow;display: none;">
     This is Yellow line!!
   </div>
</body>
</html>

Toggle Example with callback function

As mentioned earlier, in toggle method you can execute an optional function to perform some action. Following example shows how to use the callback function with toggle jQuery. As you click on the button, the yellow line will show or hide by using the toggle method while callback function will show a simple alert.

<!DOCTYPE html>
<head>
<title>jQuery Testing</title>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
   <script type="text/javascript" language="javascript">
   $(document).ready(function() {
     $(".hidetext").click(function () {
     $(".text").toggle("slow",function(){
      alert("Toggle method executed");
    });
  });
  });
   </script>
</head>
<body>
   <button class="hidetext">Toggle yellow line</button>
   <div class="text" style="background-color:yellow;display: none;">
     This is Yellow line!!
   </div>
</body>
</html>

Need Help? Contact Us.

Log in

*
*

Forgot password?

*

New User

*
*
*
*