JQuery slideToggle Example

This tutorial explains how to hide and show elements by using slideToggle() method in jQuery. The slideToggle() method display or hide the matched elements in the document. In this example, when we clicked Show/Hide button; it will show the collapsible content and hides the content, when we click the same button again. The slideToggle() method animates the width, height, background color etc of the matched elements simultaneously. The important thing is here, we should set display as none (display: none) in the CSS style sheet; otherwise the content will display directly on the page.

JQuery SlideToggle Syntax

$(selector).slideToggle();

JQuery SlideToggle Example

<!doctype html>
<head>
<title>JQuery Toggle to Show/Hide Content</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<h2>Jquery Toggle Example to Display and Hide Content</h2>
<style>
   div{
        background:orange;
        border:3px dotted red;
        color:green;
        font-family: arial narrow;
        display:none;
   }
</style>
<script type="text/javascript">
   $(document).ready(function(){
      $("#mybutton").click(function(){
         $(".mydiv").slideToggle();
      });
   });
</script>
<body>
   <button id="mybutton">Click to Show/Hide Content</button>
   <div class="mydiv">
      <p>Hello world!!!!</p>
      <p>Welcome to JQuery.</p>
      <p>It is JavaScript library.It is designed to simplify the client side scripting of HTML.</p>
      <p>Its combination of HTML, CSS and JavaScript.</p>
   </div>
</body>
</html>
  • As shown in the above program, we have used the code inside $(document).ready which is an event which fires up when document is ready. It will run once the page document object model is ready for JavaScript code to execute.
  • $(“#mybutton”).click(function()) line defines click method which occurs when an element is clicked.
  • $(“.mydiv”).slideToggle(); line defines slideToggle() method which toggles between slideUp and slideDown for the selected elements in the document. It uses class mydiv of the div element to toggle up and down of the elements which are defined within this element.

When you run the above example, you would get the following output:

ShowandHideContentPicture

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*