Toggle Hide/Show Div

Demo
Download

A great way to start utilizing the power of jQuery is to begin by learning how to toggle hiding and showing divs (or any other element) on your web site. Not only does it add a bit of flare and spice to your page, but the functionality can be achieved in 12 lines of code or less. The following tutorial will explain how to hide and show divs using jQuery with both a link and button. Once the jQuery function is established, clicking the link or button simply executes the jQuery, telling the element to either hide or show. By assigning an ‘id’ to the div element, and referencing that same ‘id’ when calling the showHide function, that div will toggle between hidden and shown.

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
 //hide and show div function
  function showHide(id){ 
  //make sure there is an id attached to the div element
   if (document.getElementById){ 
   //set the obj variable to the element's id
    obj = document.getElementById(id); 
   //if the element is currently hidden, change the css style 
   //display to '' so it will now be visible
     if (obj.style.display == "none"){ 
      obj.style.display = "";
      $(".link").html('<a href=javascript:showHide(\'hideShowDiv\');'>Hide the Skwerl</a><button onclick=javascript:showHide(\'hideShowDiv\');>Hide the Skwerl</button>');
	} else { 
	//if the element is currently visible, set the css style display to none to hide it again
	obj.style.display = "none"; 
	 $(".link").html('<a href=javascript:showHide(\'hideShowDiv\');>Show the Skwerl</a><button onclick=javascript:showHide(\'hideShowDiv\');>Show the Skwerl</button>');	
	 } 
       } 
  }
  </script>
 </head>
<body>
<div id="container" style="margin:auto;-webkit-border-radius:10px;border-radius:10px;background:#3079A0;">
 	<h2>jQuery</h2>
 	 <h3>Hide and Show Div Tutorial&</h3>
 		<div class="link">
 			<a href="javascript:showHide('hideShowDiv');"&gt;Show the Skwerl</a>
 			<button onClick="javascript:showHide('hideShowDiv');"&gt;Show the Skewrl</button>
 		</div>
 			<div id="hideShowDiv" style="display:none;border:2px dotted black;">
 				I AM A SKWERL!
 			</div>
</div>
</body>
</html>

This article has 1 comments

  1. Pingback: jQuery: Add CSS to Div using jQuery

Leave a Comment

Your email address will not be published. Required fields are marked *