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
click image to expand/collapse==>

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

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:

  1. <script language="javascript"> 
  2. function toggle() {
  3. 	var ele = document.getElementById("toggleText");
  4. 	var text = document.getElementById("displayText");
  5. 	if(ele.style.display == "block") {
  6.     		ele.style.display = "none";
  7. 		text.innerHTML = "show";
  8.   	}
  9. 	else {
  10. 		ele.style.display = "block";
  11. 		text.innerHTML = "hide";
  12. 	}
  13. } 
  14. </script>
  15.  
  16. <a id="displayText" href="javascript:toggle();">show</a> <== click Here
  17. <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.

  1. <script language="javascript"> 
  2. function toggle(showHideDiv, switchTextDiv) {
  3. 	var ele = document.getElementById(showHideDiv);
  4. 	var text = document.getElementById(switchTextDiv);
  5. 	if(ele.style.display == "block") {
  6.     		ele.style.display = "none";
  7. 		text.innerHTML = "show";
  8.   	}
  9. 	else {
  10. 		ele.style.display = "block";
  11. 		text.innerHTML = "hide";
  12. 	}
  13. } 
  14. </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:

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

That's all there is to it! =)

Here is the toogle2 JavaScript function:

  1. function toggle2(showHideDiv, switchTextDiv) {
  2. 	var ele = document.getElementById(showHideDiv);
  3. 	var text = document.getElementById(switchTextDiv);
  4. 	if(ele.style.display == "block") {
  5.     		ele.style.display = "none";
  6. 		text.innerHTML = "restore";
  7.   	}
  8. 	else {
  9. 		ele.style.display = "block";
  10. 		text.innerHTML = "collapse";
  11. 	}
  12. }

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

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. <table>
  2.    <tr>
  3.       <td>
  4.          <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px; width: 150px;">
  5.             <a id="myHeader1" href="javascript:toggle2('myContent1','myHeader1');" >collapse</a>
  6.          </div>
  7.          <div id="myContent1" style="border: 1px solid black; background-color: #CCCCCC; display: block;padding: 5px; width: 150px;">Div #1</div>
  8.       </td>
  9.       <td>
  10.          <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px; width: 150px;">
  11.             <a id="myHeader2" href="javascript:toggle2('myContent2','myHeader2');" >collapse</a>
  12.          </div>
  13.          <div id="myContent2" style="border: 1px solid black; background-color: #CCCCCC; display: block;padding: 5px; width: 150px;">Div #2</div
  14.       </td>
  15.       <td>
  16.          <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px; width: 150px;">
  17.             <a id="myHeader3" href="javascript:toggle2('myContent3', 'myHeader3');" >collapse</a>
  18.          </div>
  19.          <div id="myContent3" style="border: 1px solid black; background-color: #CCCCCC; display: block;padding: 5px; width: 150px;">Div #3</div
  20.       </td>
  21.    </tr>
  22. </table>
  23. <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. <table>
  2.    <tr>
  3.       <td style="width: 150px;">
  4.          <div id="box1" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px;">First</div>
  5.       </td>
  6.       <td style="width: 150px;">
  7.          <div id="box2" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px;">Second</div
  8.       </td>
  9.       <td style="width: 150px;">
  10.          <div id="box3" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px;">Third</div
  11.       </td>
  12.    </tr>
  13. </table>
  14. <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. var counter = 0;
  2. var numBoxes = 3;
  3. function toggle4(showHideDiv) {
  4.        var ele = document.getElementById(showHideDiv + counter);
  5.        if(ele.style.display == "block") {
  6.               ele.style.display = "none";
  7.        }
  8.        else {
  9.               ele.style.display = "block";
  10.        }
  11.        if(counter == numBoxes) {
  12.                 document.getElementById("toggleButton").style.display = "none";
  13.        }
  14. }

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. <div id="headerDivImg">
  2.     <div id="titleTextImg">Let's use images!</div>
  3.     <a id="imageDivLink" href="javascript:toggle5('contentDivImg', 'imageDivLink');"><img src="/wp-includes/images/minus.png"></a>
  4. </div>
  5. <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. function toggle5(showHideDiv, switchImgTag) {
  2.         var ele = document.getElementById(showHideDiv);
  3.         var imageEle = document.getElementById(switchImgTag);
  4.         if(ele.style.display == "block") {
  5.                 ele.style.display = "none";
  6. 		imageEle.innerHTML = '<img src="/wp-includes/images/plus.png">';
  7.         }
  8.         else {
  9.                 ele.style.display = "block";
  10.                 imageEle.innerHTML = '<img src="/wp-includes/images/minus.png">';
  11.         }
  12. }

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. <table>
  2.    <tr>
  3.       <td>
  4.          <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px;">
  5.             <a id="myHeader1" href="javascript:showonlyone('newboxes1');" >collapse</a>
  6.          </div>
  7.          <div class="newboxes" id="newboxes1" style="border: 1px solid black; background-color: #CCCCCC; display: block;padding: 5px;">Div #1</div>
  8.       </td>
  9.       <td>
  10.          <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px;">
  11.             <a id="myHeader2" href="javascript:showonlyone('newboxes2');" >collapse</a>
  12.          </div>
  13.          <div class="newboxes" id="newboxes2" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px;">Div #2</div>
  14.       </td>
  15.       <td>
  16.          <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px;">
  17.             <a id="myHeader3" href="javascript:showonlyone('newboxes3');" >collapse</a>
  18.          </div>
  19.          <div class="newboxes" id="newboxes3" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px;">Div #3</div>
  20.       </td>
  21.    </tr>
  22. </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. function showonlyone(thechosenone) {
  2.       var newboxes = document.getElementsByTagName("div");
  3.             for(var x=0; x<newboxes.length; x++) {
  4.                   name = newboxes[x].getAttribute("class");
  5.                   if (name == 'newboxes') {
  6.                         if (newboxes[x].id == thechosenone) {
  7.                         newboxes[x].style.display = 'block';
  8.                   }
  9.                   else {
  10.                         newboxes[x].style.display = 'none';
  11.                   }
  12.             }
  13.       }
  14. }

Thanks to Justin and Ulysses for helping out with the IE6 bug that was there =)
Also, thanks to Mark for suggesting to switch from name attribute to using class attribute to be compliant with W3C standards =)

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.


Here is a new demo in response to a request where only one div is displayed at any one time but also have the link to be able to hide the div as well (or basically toggle).

Demo
Div #1

Here is the HTML code:

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

Here is the JavaScript function:

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

This is very similar to the showonlyone() function except now we are toggling the content.

Here is a tutorial that shows how to hide or show content based on links on different pages.

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! OR...you can sign up for a free Dropbox account using my referral link =) If you are not aware of what Dropbox is, it is the most awesomest online backup application there and so much more...all for free.





Published by

Allen Liu

Building websites is a passion of mine. During the course of my work, I have created some snippets of code that I hope will prove useful to other developers.

455 thoughts on “How to hide, show, or toggle your div”

  1. hi Allen Liu
    The JavaScript function that toggles multiple elements simultaneously given by you helped me a lot. Thank you.
    But I need one more button like “Collapseall” that collapse all the div’s
    irrespective of which state they are in (whether Expand/Collapse).
    In the example that you have given if I click on “Toggle me button” after expanding only first div ,the remaining div’s are expanding leaving the first one collapsing. I dont want this to happen.
    Thanks
    Rajendra

    1. Hi Rajendra,

      I’m just going through the comments now. Have you since come up with a solution for the “collapse all” functionality?

      Allen

  2. Hi,
    Thanks for this code – I have used it many times :)
    I would like to show 1 div at a time and change the background image of the button for the active div (so it has a tab effect).
    My javascript skills are not great and I have had a fiddle with the code but cannot get the background image of the buttons to change.
    Are you able to help?
    Thanks
    Maddie

  3. Hello, I am finding these very useful, I am using the toggle2 & toggle3, I have a client who has a lot of information displayed on 1 page and they want the vistor to show the least amount of content as possible, I got it working great so far execpt for one problem, I will try to explain it as best as I can…I have a button to show all “main points”, which it does great, but if a “maint point” is already clicked individually to be shown/or not shown in that section, then it will only toggle all the rest except for that certain main point. I guess what I am looking for is when you click the button it either shows ALL “main points” or NO “main points” irregardless if a certain main point is being shown or not. Here is a sample test page that you can view to see what I am trying to explain, thanks in advance!

    test page –

    1. Hi Allen,
      I am new in web developing, and trying to developing a website by using weebly.

      A’ad-(the tribe of) * *Here I want to use your popular
      archaeological remains demo with png image of + / – so
      builders of land marks That i can hide list below it
      challenged to Prophet
      chastisement on
      endowed with intellect
      materialist & powerful nation
      scoffing and false arguing
      But honestly i do not know how to do it and where to past this code in my webpage in order to use this option in several pages of website. my website is not published yet, still working on it. i need your help desperately. thank you in advance.

  4. This is simple but great! My requirement is simple. On the page load, out of 4 divs, first is always displayed and other 3 are hidden. On subsequent clicks in nav menu, any one div is shown and others are hidden. Is this possible?
    Thanks a lot for help!

  5. Hello, I just found this and it has been amazingly helpful, thank you!

    I have a question though, looking at the “show only one” example, which i find very useful for what I want to do, how do you keep the headers aligned, and hide/show the content only? without moving the headers around, which is what happens in my HTML code. Thanks!

    1. Hi Sergi,

      Unfortunately, I do not understand your request. Can you give me a link to your page and tell me exactly what you are trying to accomplish?

      Allen

  6. Awesome tutorial. One question. In the ‘Collapse’ example above, I want to hide the content from the start and then collapse it. Your example is the other way around. How do I go about this? Cheers!

      1. Hi Jim,

        To have the content hidden from the start, use the following HTML instead:

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

        Finally, you just need to hide the content div as the default:

        #myContent {
            margin: 5px 10px;
            display: none;
        }

        Allen

  7. hi! great tutorial! I use your last function “showonlyonev2(thechosenone)”. Could you please tell, how should I modify it, so that when “newboxes[x].style.display = ‘block’;”, I could hide one (or several) specific div on my page (div is not connected to this function)? thanks!!

    1. Hi James,

      You can add more statements in the if block when newboxes[x].style.display == 'block'. For example:

      if (newboxes[x].style.display == 'block') {
          document.getElementById("theIdOfAnyDivElement").style.display = "none";
          document.getElementById("theIdOfAnotherDivElement").style.display = "none";
      }

      Allen

  8. Can you tell me how can I show another div after hiding the previous div thats showing by pressing a button.

  9. Thanks for this, saved me a right head ache. I’ve used the basic part of the script code at the top of this page, what I would like to know if google can still crawl the latter part of the text, ie the peek-a-boo bit as that is hidden?

    1. Never mind, I figured it out. But I’m still having trouble with the slideup effect when hiding a div. The code at http://jsfiddle.net/Nwewb/1/ isn’t working properly because it doesn’t toggle the “collapse” and “restore” text on repeated clicks. My implementation of it creates a slidedown effect on show/restore, but no slideup effect on hide/collapse, only “jump” collapse.

        1. Allen, thank you for that code, it works beautifully. But now I’m having trouble adding restore and collapse toggle images next to the toggle text, I’d like images to appear also like in your toggle5 example above. Also, is it possible to put multiple display attributes in one function block? Currently, I have several div sections so I have one function block for each display attribute, it works but it seems inefficient. Thank you so much for all the help.

          1. Hi Dave,

            Can you post a jsFiddle of what you have already? I am having trouble understanding what you are trying to accomplish. Some code would be of great help.

            Allen

  10. Hi Allen,

    Thanks for all the tricks. It would be great if you could provide code that adds the slideup and slidedown effect to the “toggle2” JavaScript function above which toggles multiple elements simultaneously and allows toggling of each DIV individually.

    Cheers

  11. Hello,

    I tried to use this script for a simple link to show and hide a div. It works well, but I need to click twice on the link to show the div. Whats the problem?

    Script:

    <a href="setVisibility('extrainfo$i');" rel="nofollow">$domain</a>

    Thanks a lot already,
    Harmen

  12. This code is great! I was looking around for a few hours trying to find something simple like this. However, there is a few things I needed in addition. For the “only one div is displayed at any one time” code, is there something that could be added to start each one hidden instead of one showing on load?

Leave a Reply

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