Post navigation

How to hide, show, or toggle your div

Are you trying to find a way to hide and show your content? The demo below shows a simple yet elegant way of toggling your content and toggling the control text via Javascript and styling.

Demo
Let's use images! click image to expand/collapse==>

We will cover how to implement this example later on in the tutorial but first let's start with a simple example.

Demo

show <== click here

 

Here is the sample HTML and Javascript code:

<script language="javascript"> 
function toggle() {
	var ele = document.getElementById("toggleText");
	var text = document.getElementById("displayText");
	if(ele.style.display == "block") {
    		ele.style.display = "none";
		text.innerHTML = "show";
  	}
	else {
		ele.style.display = "block";
		text.innerHTML = "hide";
	}
} 
</script>
 
<a id="displayText" href="javascript:toggle();">show</a> <== click Here
<div id="toggleText" style="display: none"><h1>peek-a-boo</h1></div>

By default, the peek-a-boo text is loaded when the page loads but the display attribute for the div that the content resides in is set to none so it is not visible to the visitor. When the link is clicked, the toggle() JavaScript functions executes and checks the value of the display style for the div that contains the content that we want to toggle.

If the display style is none, the function will:

  • Set the display style to block - This is executed in the else block of the function. The inner HTML content of a DOM element with a block display setting will be visible unless it is furthered controlled by CSS styling.
  • Change the link text to hide - The inner HTML of the link text, which in this case is just show, is replaced with the hide text.

If the display style is block, the function will:

  • Set the display style to none - This is executed in the if block of the function. The inner HTML content of a DOM element with the none display setting will not be visible for the viewer.
  • Change the link text to show - The inner HTML of the link text, which in this case is just hide, is replaced with the show text.

Here is a more reusable and flexible toggle function that takes 2 parameters: one for the div to hide/show and a second parameter for the div that contains the link text to be switched.

<script language="javascript"> 
function toggle(showHideDiv, switchTextDiv) {
	var ele = document.getElementById(showHideDiv);
	var text = document.getElementById(switchTextDiv);
	if(ele.style.display == "block") {
    		ele.style.display = "none";
		text.innerHTML = "show";
  	}
	else {
		ele.style.display = "block";
		text.innerHTML = "hide";
	}
} 
</script>

If you spice up this demo with some extra CSS styling, this can look like a nice little dialog box.

Demo
Hide/Show Div Demo - Click here ==>

collapse

 

This example demonstrates how CSS styling can make this look like a window that you can collapse and restore. How cool is that?!

Here is what the CSS styling looks like:


#headerDiv, #contentDiv {
float: left;
width: 510px;
}
#titleText {
float: left;
font-size: 1.1em;
font-weight: bold;
margin: 5px;
}
#myHeader {
font-size: 1.1em;
font-weight: bold;
margin: 5px;
}
#headerDiv {
background-color: #0037DB;
color: #9EB6FF;
}
#contentDiv {
background-color: #FFE694;
}
#myContent {
margin: 5px 10px;
}
#headerDiv a {
float: right;
margin: 10px 10px 5px 5px;
}
#headerDiv a:hover {
color: #FFFFFF;
}

Here is the HTML code:

<div id="headerDiv">
     <div id="titleText">Hide/Show Div Demo - Click here ==></div><a id="myHeader" href="javascript:toggle2('myContent','myHeader');" >collapse</a>
</div>
<div style="clear:both;"></div>
<div id="contentDiv">
     <div id="myContent" style="display: block;">This is the content that is dynamically being collapsed.</div>
</div>

That's all there is to it! =)

Here is the toogle2 JavaScript function:

function toggle2(showHideDiv, switchTextDiv) {
	var ele = document.getElementById(showHideDiv);
	var text = document.getElementById(switchTextDiv);
	if(ele.style.display == "block") {
    		ele.style.display = "none";
		text.innerHTML = "restore";
  	}
	else {
		ele.style.display = "block";
		text.innerHTML = "collapse";
	}
}

As requested, here is an example of a JavaScript function that toggles multiple elements simultaneously. You can either toggle each DIV individually or use the button to toggle all 3 regardless of which toggle mode they are in.

Demo
Div #1
Div #2
Div #3

This demo uses the toggle2 function as previously demonstrated and a new function called toggle3. I apologize for not being very creative on the function names. Anyway, here is the JavaScript code for toggle3:

1
2
3
4
5
6
7
8
9
10
function toggle3(contentDiv, controlDiv) {
        if (contentDiv.constructor == Array) {
                for(i=0; i < contentDiv.length; i++) {
                     toggle2(contentDiv[i], controlDiv[i]);
                }
        }
        else {
               toggle2(contentDiv, controlDiv);
        }
}

Line 2 of the function checks to see if the first argument is an array or not. If it is an array, it will also assume that the second argument is an array as well. If it is an array, the script will loop through each element and execute toggle2 with each pair of elements in the arrays. Please note that this function also assumes that both arrays are in the same order such that contentDiv[3] and controlDiv[3] are a pair that refer to the same toggle element.

If the first argument is not an array, we will just pass the arguments as is to toggle2.

Here is the HTML code for the demo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<table>
   <tr>
      <td>
         <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px; width: 150px;">
            <a id="myHeader1" href="javascript:toggle2('myContent1','myHeader1');" >collapse</a>
         </div>
         <div id="myContent1" style="border: 1px solid black; background-color: #CCCCCC; display: block;padding: 5px; width: 150px;">Div #1</div>
      </td>
      <td>
         <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px; width: 150px;">
            <a id="myHeader2" href="javascript:toggle2('myContent2','myHeader2');" >collapse</a>
         </div>
         <div id="myContent2" style="border: 1px solid black; background-color: #CCCCCC; display: block;padding: 5px; width: 150px;">Div #2</div
      </td>
      <td>
         <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px; width: 150px;">
            <a id="myHeader3" href="javascript:toggle2('myContent3', 'myHeader3');" >collapse</a>
         </div>
         <div id="myContent3" style="border: 1px solid black; background-color: #CCCCCC; display: block;padding: 5px; width: 150px;">Div #3</div
      </td>
   </tr>
</table>
<input type="button" value="Press me to toggle all 3 DIVs" onClick="toggle3(['myContent1', 'myContent2', 'myContent3'], ['myHeader1', 'myHeader2', 'myHeader3']);">

All the excitement is jammed into line 23 where we call the toggle3 function and pass over 2 arrays: one array containing all the content div ids and another array containing the header div ids. The rest is history =)


This demo was written in response to a request. We start off with some hidden divs and each click of the button will reveal one div at a time. When we have revealed all the divs, the button will disappear.

Demo

Here is the HTML code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<table>
   <tr>
      <td style="width: 150px;">
         <div id="box1" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px;">First</div>
      </td>
      <td style="width: 150px;">
         <div id="box2" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px;">Second</div
      </td>
      <td style="width: 150px;">
         <div id="box3" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px;">Third</div
      </td>
   </tr>
</table>
<input id="toggleButton" type="button" value="Show me the money!" onclick="counter++; toggle4('box');">

The HTML code contains 3 hidden divs to start off with. The button will launch the toggle4 JavaScript function and pass over the prefix of the div IDs. Each div id is named with the prefix box and a number following the name. For example, box1, box2, and box3. This is important for our JavaScript function. In addition, it increments the counter by 1 each time. This variable is initialized in our function.

Here is the JavaScript code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var counter = 0;
var numBoxes = 3;
function toggle4(showHideDiv) {
       var ele = document.getElementById(showHideDiv + counter);
       if(ele.style.display == "block") {
              ele.style.display = "none";
       }
       else {
              ele.style.display = "block";
       }
       if(counter == numBoxes) {
                document.getElementById("toggleButton").style.display = "none";
       }
}

Lines 1 and 2 will initialize two very important variables for us:

  1. counter - This variable will help us determine which box we will need to toggle.
  2. numBoxes - This variable represents the total number of boxes. This is important for us to know when we should hide the button.

Line 4 accesses the div we will need to toggle based on the name that is passed over as the argument and the counter. When these 2 values are concatenated, we get the name of the div we will need to toggle.

Lines 5-10 tells the same old story as before for toggling the content.

Lines 11-13 tests to see if we have reached our maximum number of divs to toggle. If so, it will access the toggle button and set the display attribute to none.


By popular demand, here is a demo that uses images instead of the Expand/Collapse text.

Demo
Let's use images!

This demo uses plus and minus images for hiding and showing your div dynamically via JavaScript.

Here is the HTML code:

1
2
3
4
5
<div id="headerDivImg">
    <div id="titleTextImg">Let's use images!</div>
    <a id="imageDivLink" href="javascript:toggle5('contentDivImg', 'imageDivLink');"><img src="/wp-includes/images/minus.png"></a>
</div>
<div id="contentDivImg" style="display: block;">This demo uses plus and minus images for hiding and showing your div dynamically via JavaScript.</div>

Everything is pretty much the same as before except the image tag is used instead of the Expand/Collapse text.

Here is the JavaScript code:

1
2
3
4
5
6
7
8
9
10
11
12
function toggle5(showHideDiv, switchImgTag) {
        var ele = document.getElementById(showHideDiv);
        var imageEle = document.getElementById(switchImgTag);
        if(ele.style.display == "block") {
                ele.style.display = "none";
		imageEle.innerHTML = '<img src="/wp-includes/images/plus.png">';
        }
        else {
                ele.style.display = "block";
                imageEle.innerHTML = '<img src="/wp-includes/images/minus.png">';
        }
}

The toggle5 JavaScript function is pretty much the same as the rest of the toggle functions except that it switches the img tags instead of text.


Here is a new demo in response to a request where only one div is displayed at any one time.

Demo
Div #1

Here is the plain HTML code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<table>
   <tr>
      <td>
         <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px;">
            <a id="myHeader1" href="javascript:showonlyone('newboxes1');" >collapse</a>
         </div>
         <div name="newboxes" id="newboxes1" style="border: 1px solid black; background-color: #CCCCCC; display: block;padding: 5px;">Div #1</div>
      </td>
      <td>
         <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px;">
            <a id="myHeader2" href="javascript:showonlyone('newboxes2');" >collapse</a>
         </div>
         <div name="newboxes" id="newboxes2" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px;">Div #2</div>
      </td>
      <td>
         <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px;">
            <a id="myHeader3" href="javascript:showonlyone('newboxes3');" >collapse</a>
         </div>
         <div name="newboxes" id="newboxes3" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px;">Div #3</div>
      </td>
   </tr>
</table>

Clicking on the links will execute the showonlyone JavaScript function and pass on the name of the div id.

Here is the showonlyone JavaScript code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function showonlyone(thechosenone) {
      var newboxes = document.getElementsByTagName("div");
            for(var x=0; x<newboxes.length; x++) {
                  name = newboxes[x].getAttribute("name");
                  if (name == 'newboxes') {
                        if (newboxes[x].id == thechosenone) {
                        newboxes[x].style.display = 'block';
                  }
                  else {
                        newboxes[x].style.display = 'none';
                  }
            }
      }
}

Thanks to Justin and Ulysses for helping out with the IE6 bug that was there =)

Line 2 will find all our divs with the newboxes name attribute and place them in an array. Lines 3-10 will loop through these divs and check to see if the id of the div matches the id that was passed over to the function. If there is a match, the function will set the display attribute to block which will make the div and all its contents visible. If the id does not match, the display attribute will be set to none which will make the div and all its contents hidden.

If there any other demos/tutorials that you would like to see on this subject, please feel free to comment below and I will try my best to implement it.

Note: If you have an issue with your code, please give me a URL to work with. It's extremely difficult for me to help if I cannot actually see the code.

UPDATE: Since this post has been pretty popular, I felt is was my duty to update it newer methods that was not available at the time of writing this blog. Nowadays, it is much easier to use jQuery to hide or show content.

If you found that my code was helpful in any way, shape, or form and would like to buy me a beer, please use the Donate button below =) Cheers!

 

 


 

 

 

This entry was posted in javascript and tagged , , , , , , , , by Allen Liu. Bookmark the permalink.