How to Hide Div Code jQuery
- 1). Download the JQuery library jquery-1.5.1min.js from the download link provided in the References section. In the download dialog box, select "Save As..." and save the library to your desktop.
- 2). Copy and paste the following code into Notepad, and save it as hidediv.html on your desktop. This consists of four layers of nested DIVs with links to display or hide each nested DIV. The DIV ID and link IDs such as "sheep," "sheep_1," etc. indicate the section name and nested DIV level.
<html><head>
<script type='text/javascript' src='jquery-1.5.1.min.js'></script>
</head><body>
<div id='sheep'>Baa baa black sheep, have you any wool?
<a href='#a1' id='sheep' class='showOpt'></a>
<div id='sheep_1'>Yes sir, yes sir, three bags full,
<a href='#a1' id='sheep_1' class='showOpt'></a>
<div id='sheep_2'>One for my master, one for my dame,
<a href='#a1' id='sheep_2' class='showOpt'></a>
<div id='sheep_3'>And one for the little boy that lives in our lane.
</div> </div> </div> </div>
<script>
</script><body></html> - 3). Copy and paste the following "toggleDiv()" JQuery function, above the line "</script></body></html>," so that it runs after all the HTML objects have been loaded. This JQuery function takes the show-or-hide link ID, e.g. "sheep_1," as a parameter and hides or shows the next nested DIV depending on whether the attribute "isShowing" is currently set to "yes" or "no." It uses the JQuery "fadeToggle()" method to toggle between the two states. The final three lines hide all levels from the grandchild level and below to ensure that only the currently selected child level is displayed on selection.
jQuery.fn.toggleDiv=function(id){
$('div:[id="'+id+'"]').children('div').fadeToggle('slow');
if(($('div:[id="'+id+'"]').children('div').attr('isShowing'))=='no'){
$('div:[id="'+id+'"]').children('div').attr('isShowing','yes');
$('a:[id="'+id+'"]').html('(hide...)');
}else {
$('div:[id="'+id+'"]').children('div').attr('isShowing','no');
$('a:[id="'+id+'"]').html('(show...)');
}
$('div:[id="'+id+'"]').children('div').find('a').html('(show...)');
$('div:[id="'+id+'"]').children('div').find('div').hide();
$('div:[id="'+id+'"]').children('div').find('div').attr('isShowing','no');
} - 4). Copy, and paste the click event function after the end of the "jQuery.fn.toggleDiv" function. Whenever a link with class "showOpt" is clicked, it calls the toggleDiv function with the current ID as the parameter.
$('a:[class="showOpt"]').click(function(e){
$().toggleDiv(this.id);
}); - 5). Copy, and paste the following line after the end of the preceding click-event function. When the page loads, all the nested DIVs are displayed by default. This line needs to be added, so that just when the page finishes loading, all the DIVs below the "sheep" DIV are hidden.
$().toggleDiv('sheep'); - 6). Save hidediv.html and test the page by clicking on the show and hide links.
Source...