jQuery slideToggle() method toggles between slideUp() and slideDown() methods. If the html elements are slid down then this method will slide them up and if the elements are slid up then this method will slide them down.
jQuery slideToggle() Syntax
$(selector).slideToggle(speed, callback_function);
Here $(selector) is to select html elements.
speed is an optional parameter and it can be passed in milliseconds or “slow” or “fast”.
callback_function is an optional parameter as well. This function executes when the effect is complete. In this case, it will execute when the slide toggle effect is complete. We will see the example of it in this article as well.
jQuery slideToggle() Example
In the following example we are applying the slide toggle effect on the paragraph, on the h2 element click event, we are calling slideToggle() method on paragraph, which will make the paragraph disappear with a slide up effect and when we click the h2 heading again, the paragraph will reappear with a slide down effect.
The slideToggle effect happens only when we click the h2 heading because we are calling slideToggle() method inside h2 element click function.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("h2").click(function(){ $("#para").slideToggle(); }); }); </script> </head> <body> <h2>jQuery slideToggle effect example, Click here</h2> <p id = "para">This tutorial is published on beginnersbook.com. This paragraph will disappear with a slide up effect once we click on the h2 heading and when we click on the h2 heading again, this para will reappear with a slide down effect.</p> </body> </html>
Output:
Before h2 heading is clicked:
After h2 heading is clicked:
After h2 heading is clicked again:
jQuery slideToggle() Example with speed and callback function parameters
We can also pass speed and callback function as parameters to the slideToggle() method. Speed parameter is to adjust the speed of the effect and callback function executes when the effect is complete. Here we are setting up an alert message in the callback function which will execute when the slide toggle effect is complete.
$(document).ready(function(){ $("h2").click(function(){ $("#para").slideToggle("slow", function(){ alert("The slideToggle effect is complete"); }); }); });
Output:
Leave a Reply