Toggle DIV element using jquery

What is Toggling?
Basically a show/hide feature for your webpage elements. For example, you may have a login box in your webpage, and you want your visitors to click on a button for showing or hiding the element.

This tutorial will show you how to implement a simple toggle effect in your webpage using jQuery.

As always, we will require some HTML content first

  1.  
  2. <a id="clickMe">Toggle my text</a>
  3. <br />
  4. <div id="textBox">This text will be toggled</div>

jQuery code
This is the code that makes the 'textBox' element toggle

  1. $("#textBox").toggle();

But we want to toggle the element only when you click on 'Toggle my text' link. And this code will make it happen:

  1. $(document).ready(function() {
  2.   $("#clickMe").click(function() {
  3.     $("#textBox").toggle();
  4.   });
  5. });

Final Code:

  1. <html>
  2.   <head>
  3.     <title>jQuery test page</title>
  4.     <script type="text/javascript" src="jquery.js"></script>
  5.     <script type="text/javascript">
  6.       $(document).ready(function() {
  7.         $("#clickMe").click(function() {
  8.           $("#textBox").toggle();
  9.         });
  10.       });
  11.     </script>
  12.   </head>
  13.   <body>
  14.     <a id="clickMe">Toggle my text</a>
  15.     <br />
  16.     <div id="textBox">This text will be toggled</div>
  17.   </body>
  18. </html>

 

Share: