Last Updated on September 22, 2022 by Roshan Parihar
In this tutorial, learn how jQuery toggle div visibility on button click. The short answer is to use the toggle()
function of jQuery to toggle on click.
You can also use the slideToggle()
function of jQuery to toggle display the div element. Let’s find out with the examples given below.
Method 1: Toggle Div Visibility On Button Click Using jQuery toggle()
If you want to toggle <div>
visibility, you can use the jQuery toggle()
function. It’s a simple function that performs both shows and hides effects on click.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<script> $(document).ready(function(){ $("button").click(function(){ $("div").toggle(); }); }); </script> <button type="button">Toggle div</button> <div> <p>This is the div content one.</p> <p>You can add more content here.</p> <p>Toggle your div content using this example.</p> </div> |
Output
This is the div content one.
You can add more content here.
Toggle your div content using this example.
The above example contains the button element and the div content. When you click the button, it shows and hides the content.
To make the toggle speed slow, you can pass speed in milliseconds as the argument of the toggle()
function. If you want to make a 2-second delay in the toggle effect, you can pass 2000
as the argument.
Method 2: Using jQuery slideToggle()
Function
In addition to the above method, you can also use the slideToggle()
function of jQuery. The function of jQuery toggle div visibility with some sliding effect.
1 2 3 4 5 6 7 8 9 10 11 12 |
<script> $(document).ready(function(){ $("button").click(function(){ $("div").slideToggle(); }); }); </script> <button type="button">Slide Toggle div</button> <div> <p>Welcome to TutorialDeep!</p> <p>How are you today?</p> </div> |
Output
Welcome to TutorialDeep!
How are you today?
You can click the above button to check the slide effect with toggle div content visibility using jQuery. It does not require to use of any delay in seconds for the sliding effect. The function is a built-in function of jQuery for the sliding effect.
You May Also Like to Read