In this guide, we will discuss the jQuery toggle effect. It is used to toggle between hidden and displayed html elements. Which means it hides the shown element and when clicked again it shows the hidden element.
Syntax
selector.toggle( speed, [callback]);
Here selector is any jQuery selector that is used to select an html element on which this toggle effect is applied.
speed: This parameter is optional and can be provided in milliseconds or the values such as “slow” or “fast”.
[callback]: This is also an optional parameter, it represents a function that executes when the toggle animation is complete.
jQuery toggle() Effect Example
In the following example we have applied the toggle effect on the paragraphs on the button click event. When the button is clicked first time, it hides all the paragraphs present on the html page and when clicked again, it shows them again.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").toggle(); }); }); </script> </head> <body> <h2>jQuery toggle effect example</h2> <p>This tutorial is published on beginnersbook.com. This para can be hidden and displayed using toggle button.</p> <button>toggle</button> </body> </html>
Output:
Page loaded, we have not clicked the toggle button yet:
After toggle button is clicked:
After toggle button is clicked again:
jQuery toggle effect with speed parameter
We can pass speed in milliseconds for the toggle effects. In the following example paragraph element will take 2000 milliseconds time to get hidden and displayed completely. Alternatively we can pass the values such as “slow” and “fast” in instead of milliseconds value.
$(document).ready(function(){ $("button").click(function(){ $("p").toggle(2000); }); });
jQuery toggle effect with callback parameter
Lets take the same example that we have seen above, we are just changing the jQuery part in the script area of the example: Here we have passed the speed parameter as “fast” which means the toggle effect will be fast and in the callback function we are displaying an alert message that “All paragraphs are now hidden”.
$(document).ready(function(){ $("button").click(function(){ $("p").hide("fast", function(){ alert("All paragraphs are now hidden"); }); }); });
This will produce the following output when we click the toggle button:
Leave a Reply