jQuery - toggle( fn, fn2, fn3,... ) Method



Description:

The toggle( fn, fn2, fn3,... ) method toggles among two or more function calls every other click.

Whenever a matched element is clicked, the first specified function is fired, when clicked again, the second is fired, and so on.

Syntax:

Here is the simple syntax to use this method −

selector.toggle( fn, fn2, fn3,... )

Parameters:

Here is the description of all the parameters used by this method −

  • fn, fn2, fn3....: The functions to be executed against clicks.

Example:

Following is a simple example a simple showing the usage of this method −

<html>
<head>
<title>The jQuery Example</title>
   <script type="text/javascript" 
   src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
      </script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {
      $("div").toggle(
         function () {
           $(this).css({"background-color":"red"});
         },
         function () {
           $(this).css({"background-color":"yellow"});
         },
         function () {
           $(this).css({"background-color":"black"});
         }
       );

   });

   </script>
   <style>
      .div{ margin:10px;padding:12px;
             border:2px solid #666;
             width:200px;
           }
  </style>
</head>
<body>
   <span>Click below square to see the result:</span>
   <div class="div" style="background-color:blue;"></div>
</body>
</html>
Advertisements