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.
We will cover how to implement this example later on in the tutorial but first let's start with a simple example.
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 theelseblock of the function. The inner HTML content of a DOM element with ablockdisplay 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 justshow, is replaced with thehidetext.
If the display style is block, the function will:
- Set the display style to
none- This is executed in theifblock of the function. The inner HTML content of a DOM element with thenonedisplay 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 justhide, is replaced with theshowtext.
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.
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.
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.
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:
- counter - This variable will help us determine which box we will need to toggle.
- 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.
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.
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 class="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 class="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 class="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("class"); 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 =)
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).
Here is the 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-2" href="javascript:showonlyonev2('newboxes1-2');" >toggle</a>
</div>
<div class="newboxes-2" id="newboxes1-2" 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-2" href="javascript:showonlyonev2('newboxes2-2');" >toggle</a>
</div>
<div class="newboxes-2" id="newboxes2-2" 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-2" href="javascript:showonlyonev2('newboxes3-2');" >toggle</a>
</div>
<div class="newboxes-2" id="newboxes3-2" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px;">Div #3</div>
</td>
</tr>
</table> |
Here is the JavaScript function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | function showonlyonev2(thechosenone) { var newboxes = document.getElementsByTagName("div"); for(var x=0; x<newboxes.length; x++) { name = newboxes[x].getAttribute("class"); if (name == 'newboxes-2') { if (newboxes[x].id == thechosenone) { if (newboxes[x].style.display == 'block') { newboxes[x].style.display = 'none'; } else { newboxes[x].style.display = 'block'; } }else { newboxes[x].style.display = 'none'; } } } } |
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.
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
Hi Maddie,
Can you share your fiddle? It doesn’t matter if the image change doesn’t work.
Allen
Sorry I don’t think it was showing my URL in my comment, here it is again test page
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 -
This is very useful for me for to make hidden and toggle fields:)
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!
This is certainly possible! You can use the concepts here in combination with this article on hiding/showing content based on URLs to come up with a custom solution to fit your needs. I am assuming that your nav clicks reload the page.
Allen
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!
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
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!
Sorry to confuse, I mean, hide it on page and then display it on click.
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:
Allen
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!!
Hi James,
You can add more statements in the
ifblock whennewboxes[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
http://jsfiddle.net/Nuker_Viper/JvLDx/17/
i cannot seem to get it working
I have selected “no wrap (head)” which loads the JS for you. It was not loading with your previous configuration:
http://jsfiddle.net/JvLDx/18/
Allen
Can you tell me how can I show another div after hiding the previous div thats showing by pressing a button.
Here is a simple example:
http://jsfiddle.net/axl163/kGkKt/
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?
This is a very good question and there has been many discussions on it. Here is one such discussion which I found to be pretty good:
http://webmasters.stackexchange.com/questions/1377/how-bad-is-it-to-use-display-none-in-css
I hope this helps.
Allen
You’ve saved me a lot of time, Thank You and … don’t stop!
Hi Allen,
Any chance you can provide the code to show img AND text tags together in toggle5 above?
Thank you.
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.
Here you go:
http://jsfiddle.net/Nwewb/46/
You should toggle after detecting what the element’s display attribute is.
Allen
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.
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
http://jsfiddle.net/codehunter487/TgDdc/
Never mind, got it. Thanks again, couldn’t have done it without you.
Thank you sir, that’s exactly what I needed.
Your very welcome! =)
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
Hi Dave,
Here you go: http://jsfiddle.net/Nwewb/1/ =)
I hope this helps.
Allen
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
Hi Harmen,
Unfortunately, I am only seeing a small portion of your code but I would recommend binding your a tag. Here is an example:
$(document).ready(function() { $(a).on('click', function() { setVisibility("extrainfo$i"); }); });Of course, you would need to refine the jQuery selector because the example I gave above selects all your a tags.
I hope this helps.
Allen
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?
Hi Jeremy,
I have received many similar requests. I have updated the post to cover this but all you need to do is to add the CSS so that the display attribute of your divs are set to none.
Allen
[...] ist es nicht, und sooo viel Code auch nicht) hab ich mich bei sowas an folgendes Tutorial gehalten: How to hide, show, or toggle your div Ich denke, das macht genau das, was du brauchst =) mit nur ein paar Zeilen [...]