How to use jQuery slideToggle function

In this post, I will show you how can you toggle any element based on any event. For example, on click of any button you want to show/hide any div element. You can easily achieve this by setting css of the div. I will show you how you can achieve it using jQuery without setting any css and also add slide effect while showing/hiding.

jQuery provides a .slideToggle() function which slide up or down any element. Let's see an example.

Place a button and a div with some text in it on the page.
<asp:Button ID="btnToggle" runat="server" Text="Toggle Text" />
<div id="dvText">
   jQuery By Example rocks!!!!
   jQuery By Example rocks!!!!
   jQuery By Example rocks!!!!
   jQuery By Example rocks!!!!
</div>
On click on this button, we will show/hide the div. See below jQuery code.
$(document).ready(function(){
   $('#btnToggle').click(function(){
      $('#dvText').slideToggle(1000);
      return false;
   });
});
As you can see from the code, I have passed 1000 as an argument in slideToggle function. This value is in milliseconds which tells how fast the div should slide up or down. You can also pass 'fast' or 'slow' value as parameter in this function. 'fast' and 'slow' denotes 200 and 600 milliseconds respectively.
See live Demo and Code.
.slideToggle() function also make use of display css property internally. while sliding up when yhe height of the element reaches 0 it stores "none" in display property and while slide down it stores "inline" value of display property. Based on the value of display property it determines whether to slide up or down.

Feel free to contact me for any help related to jQuery, I will gladly help you.
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..