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 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.
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 name="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 name="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 name="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("name"); 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.
Allen i have a question for you…
When it says “document.getElementById”, i was trying to do “document.getElementByClass” but it doesn’t work…
How do we say to get a class (“liveLyrics”) that is inside of:
e.g.
head
style type=”text/css”
#background {
height: 550px;
width: 1008px;
background-image: url(http://example.png);
background-repeat: no-repeat;
float: left;
}
#background #rightLyrics {
height: 406px;
width: 727px;
margin-top: 38px;
margin-left: 41px;
}
#background #rightLyrics .liveLyrics {
height: 45px;
width: 90px;
margin-top: 40px;
margin-right: 56px;
float: left;
}
style
head
body
div id=”background”
div id=”rightLyrics”
div class=”liveLyrics”
img src=”example.gif”
div
<div class="liveLyrics"
<img src="example.gif"
div class=”liveLyrics”
img src=”example.gif”
div
div
div
body
html
sorry, this doesn’t accept html tags… please remove my previouse coments…
Hi David,
I think the function you are looking for is
document.getElementsByClass()and notdocument.getElementByClass.Allen
Sorry that’s not enough information… because the class “liveLyrics”
is inside of the id “background” and id “canais”…
what should i put inside of document.getElementsByClass()?
e.g. document.getElementsByClass(background canais canal)??
Thanks for your time, you’re very helpful :)
Hi David,
You should just be able to call
document.getElementsByClass("liveLyrics")directly to access elements with the “liveLyrics” class. I’m not sure how much control you have on this but I would recommend using the jQuery library. Once you have jQuery going on your site, the element(s) selector code is just$(".liveLyrics")=)Allen
I think it’s impossible, because even when i take the class “liveLyrics”
and put them out of the id’s…. its still doesn’t work…
Can you give me the URL to your site?
Allen
Hi Allen,
I note most of the code I posted did not show so will send via email.
Regards
Rod
Hi Allen,
Thank you, this works fine in Demo.html.
However when I moved it into my eCommerce site I had to move the CSS into its own style sheet which worked fine, However when I add the rest of the code to the website the HTML editor its changing the code for some reason – note the addition of the “[CDATA]“.
// <![CDATA[
function showonlyone(thechosenone) {
var newboxes = document.getElementsByTagName("div");
for(var x=0; x
Would this be the reason it's not working? Can the rest of the code be made to work with the "[CDATA]” included in the code?
I can post a link to the site if that would help.
Regard
Rod
Hi Rod,
The CDATA just tells the XML parser to ignore whatever is inside the CDATA section. It should not have an effect. I took a look at your code and it was missing the div name “newboxes” for the 3 divs. Your HTML part should look like this:
<div class="outerBox"> <div class="boxHeader"><a id="myHeader1" href="javascript:showonlyone('box1');" rel="nofollow">Expand</a></div> <div id="box1" class="contentBox" name="newboxes">Div #1</div> </div> <div class="outerBox"> <div class="boxHeader"><a id="myHeader2" href="javascript:showonlyone('box2');" rel="nofollow">Expand</a></div> <div id="box2" class="contentBoxHidden" name="newboxes">Div #2</div> </div> <div class="outerBox"> <div class="boxHeader"><a id="myHeader3" href="javascript:showonlyone('box3');" rel="nofollow">Expand</a></div> <div id="box3" class="contentBoxHidden" name="newboxes">Div #3</div> </div>Notice that I added name=”newboxes” to the 3 content divs. That is what worked for me on my end.
I hope that helps.
Allen
Hi Allen
The fact that you have kept this tread going all these years is amazing.
If I could also now ask for your help, no matter how I import the above example with 3 DIV’s where only one is visible at a time it will not work. If you could email a full working example it would be greatly appreciated.
Regards
Rod
Hi Rod,
Thanks for the comment. I have put all the code here for you. Just copy and paste everything to a text editor and name with a “.html” extension (e.g. demo.html). The double-click that file and your browser should automatically open it up.
<html> <head> <title>Demo to show only one div at a time</title> <script type="text/javascript"> 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'; } } } } </script> <style type="text/css"> .outerBox { width: 100px; float: left; text-align: center; } .boxHeader { border: 1px solid blue; background-color: #99CCFF; padding: 5px; } .contentBoxHidden { border: 1px solid black; background-color: #CCCCCC; display: none; padding: 5px; } .contentBox { border: 1px solid black; background-color: #CCCCCC; display: block; padding: 5px; } </style> </head> <body> <div class="outerBox"> <div class="boxHeader"> <a id="myHeader1" href="javascript:showonlyone('box1');" rel="nofollow">Expand</a> </div> <div class="contentBox" name="newboxes" id="box1">Div #1</div> </div> <div class="outerBox"> <div class="boxHeader"> <a id="myHeader2" href="javascript:showonlyone('box2');" rel="nofollow">Expand</a> </div> <div class="contentBoxHidden" name="newboxes" id="box2">Div #2</div> </div> <div class="outerBox"> <div class="boxHeader"> <a id="myHeader3" href="javascript:showonlyone('box3');" rel="nofollow">Expand</a> </div> <div class="contentBoxHidden" name="newboxes" id="box3">Div #3</div> </div> </body> </html>I did a lot of cleanup to the original code:
I hope this works out for you.
Allen
Thanks for the script . The excellent thing about the script is its so simple that I can edit in my choice . Loved it
hi allen love your snippets man, you are awesome, one question you dont you work on jquery-ajax :-( , please work on it, so that we can get it. please regards waqas
Thanks for the comment Waqas! I usually do snippets for solutions that are hard to find on the internet. I feel that all aspects of jQuery AJAX is pretty nicely covered out there. Is there a specific issue you are having with AJAX with jQuery or you would just like to see a general tutorial on the topic?
hello….
i m using div but this tag not using name property.. so give me solution
Hi Rahul,
I would recommend to use jQuery implementation instead. One of the many advantages of using jQuery is the ease of selecting almost any element or group of elements.
Here is my post of the jQuery implementation of the show/hide post.
Instead of using the selector where it is looking for elements based on the name attribute, you can choose the child elements of a certain parent element.
Let’s say you have the following HTML for your divs:
The JavaScript only changes slightly for the “showonlyone” function:
I have not tested this but the idea is to choose all the child elements of the parent element which is “parentDiv” in this case. We are only using id’s here so there is no need to base this function on the “name” attribute.
I hope this helps.
Allen Liu
(sorry, found the fade section!) http://www.randomsnippets.com/2011/04/10/how-to-hide-show-or-toggle-your-div-with-jquery/ !
No problem. I was just about to reply to you with the same response =)
Allen
Brilliant stuff!!! Got it working relatively quickly and it works cross browser :-) Thanks so much.
Have you had any thoughts on how the div could fade in/out as opposed to just popping?
Ty so much dude !
Dude you rule!
Haha…thanks!
Thank you SO MUCH! I am currently making a website, and this helps SO MUCH. I will be sure to donate (let me make some Paypal cash first :D)
Thanks so much for posting these. You are the ONLY person that I have seen post these type of show/hide scripts in a clear and easy to follow way. This page has been a HUGE help for my development project!!!!
Wow, as someone very new to web designing, I am thrilled to see someone so supportive as to stick with a topic so long and help so many people.
I have an image (tree with many hearts) and I want to use DreamWeaver to create hotspots for each heart. Then, when a user hovers (or clicks) on a heart, a different quote appears.
Here is the site: http://www.oss-shamrocks.com/Mrs%20Newport.html
I would love your input. Thank you so much!
Hi Ken,
At first glance, I thought the overall image was cute however, the quotes are not popping up for me when I click on the hearts. I used FireFox 4/Mac OSX. If you hover over it long enough though, a popup does occur but that is the natural response of the HTML.
Allen
i have getting both div content simultaneously over each other when page load at beginning. after clicking it become fine and working. ho wto show only one content at starting
You can add the styling code to the div to hide it from the start:
thanx for helping me… i have wasted 5 hrs for searching this….
Hi, im from argentina, sory my english
can i add an effect, like ´slide´or ´fade´?
thancks
Please check out my other post relating to hide, show, toggle divs with jQuery.
I’m trying out your first toggle code, using radio buttons as the switch, but when I click, the hidden div shows under (or over) the div underneath it rather than moving it down.
Essentially, I found a site that does what I’m looking for:
http://www.pimsleurapproach.com/learn-german.asp
If you click the “No” radion button where it asks about your billing address, the billing address entry area shows, and everything under the cart moves down. make sense?
I could just grab those folks code, I’m sure, but theyre using loads and loads of nested tables, and I just want to use divs.
Any ideas?
Hi Chuck,
I’m sure it is just all in the way your site is laid out. Can you give me the url to the page you are working on? This way it will be much easier for me to help you out. I’m still a bit confused to what you describe at first because you mentioned “the hidden div shows under (or over).” Maybe seeing your actual code and example could clarify this.
Allen
Sadly, its on an internal server…I’ll be working on it when I get home tonight, maybe I can create a sample that recreates the issue.
No problem. I’ll be able to look at it tonight if you can prepare the sample page.
Allen
Got it!
I had a container div surrounding the div I needed to expand and collapse, and the div next to it that just contained content.
In that div I had “display: inline-table” (dunno why I put it in, it wasnt needed). Once I removed that, the code works perfectly.
Thanks!
~C
Awesome! I’m glad you were able to resolve it. Inline vs. Block placement will definitely give different effects in the layout of your div.
Allen
I’m trying to hide/show a particular post on the same page when you click on the link instead of it taking you to another page. Any idea how to do this?
Hi Tyler,
You can try the following code:
Allen
[...] [...]
Hi.
I’d like to use this but here is my situation. I have two divs (one with a random image generator of landscape photos and one with a random image generator of portrait photos. Upon page load I’d like for either one to be displayed. Basically, I would like it to be random.
Any ideas?
I’m using the Peek-a-boo demo, and I was wondering what part of the code I would have to change in order to have unrelated topics on the same page be hidden or shown independently.
At this point, clicking the hide/show on one div affects all the divs, which defeat the purpose of what I’m trying to do.
I also have very limited JS experience, which doesn’t help much.
Please check out my “checkonlyone” demo. I think that may be what you are looking for. If not, please let me know. If possible, provide me with a link to your site.
Thanks,
Allen
I actually figured it out after talking with a buddy that does Java Programming. what i needed was to change the “function toggle();” to “function [something unique for each div to be hidden/shown]();” These tutorials are fantastic.
I’m trying to recreate the hide/show divs on this page for the bios http://morrisonplc.com/
i understand the concept but i’m not quite sure on how to apply it to the site i’m working on at the moment.
i’m just doing short 1-2 line bios with a picture on the left
so:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed pharetra sem vitae leo cursus nec cursus est blandit. Mauris ut mi in magna adipiscing fringilla a ac enim.
and i want to make the image for each person a trigger to show a mid box with a larger image and more complete text about the person.
any help would be much appreciated or a pointer in the right direction.
Hi Robert,
It looks like you came up with a nice solution. Nice job!
Allen
the website i linked is the one i want to mimic not the one i’m working on :p unfortunately ^^
and i always forget that coding doesn’t show up properly in boxes.
Hi Robert,
Ooops…sorry for misunderstanding your original comment. You can definitely make this work with the concepts shown above except the divs, with each persons bio, that you are going to show/hide are all going to be in that middle box with “display:none”. This way nothing shows up at first. The link for each person’s bio would just show that particular bio or div. For the cool effects, you may want to look at jQuery: http://jqueryui.com/demos/dialog/#modal
I also have a jQuery demo where you can hide/show elements which is MUCH simpler.
Allen
hi there. i been searching this codes. and unfortunately i don’t know how to make it work. i used the “peek-a-boo” demo and make it work. but if i use any other codes here i dont know why its not working. i want to use the ‘showonlyone’ but cant make it work. can you help me please. i’m using firefox as my browser.
Hi Dee,
I can try to help you out. Can you give me the url to your site so that I can see what you did?
Allen
its still on draft and im still testing the codes on notepad.
and im planning to add it to facebook fan page. will the codes properly work there?
the problem is it wont change to div#2 when i click the second tab. it will just refresh.
thanks for the fast reply.
Hi Dee,
Unfortunately, I cannot help out unless I see the page and the code you used.
Allen
If you cannot give me a live page, then can you tell me what error message you get? FireFox/FireBug should be giving you JavaScript error messages.
Hi I have used toggle2 along with toggle3 as demoed here. however on IE the content displays behind the elements below it instead of pushing them all down. any ideas what might be wrong? you can view the issue here http://www.peelentertainmentgroup.com/what-we-do
thanks
toyin
Hi Toyin,
It looks like the issue is addressed. If so, please share what you did to solve it.
Thanks,
Allen
Hi no its not but I am working hard on it. hope to get a break thruough soon. did you check it on IE? what version. It works fine on firefox.
cheers
toyin
I see. I used FF. What version of IE are you using? I will check it out when I get in front of a PC later on today.
yeah, using ie8 thanks
Looks like you need a:
<div style=”clear: both;”></div>
before
<div class=”bottom-art-Sheet-bkg-inline”>
Thanks a lot Allen. but that didn’t work. I have finally solved the problem by putting border:1px solid #cccccc in the style for that same div you mentioned i.e.
Very bizarre solution but worked. still dont understand why though.. thanks a lot for the javascript code though… very brilliant.
Definitely odd but that is IE for ya =) I’m glad got it working.
Thank you man!
Thank you so much! So versatile and well explained, too. Just a little hard to see where one option ends and the next begins, however.
Thanks for the suggestion! I added some <hr> tags in there. Hopefully, that will make is a bit easier to visualize.
Allen
Many thanks Allen Liu/Knix, nice ideas, nicely illustrated!- i’ll make good use of them :)
the only room for improvement I see now would be in the code, some DIV tags seem to be missing an end bracket, especially in the showonlyone example, in which i was particularly interested.
Again, Thank you!
Great catch! I just fixed up the code. Thanks!
Hi! How can I make
1. a bottom toolbar for my website to toggle toward upside not downside with all elements closed and ShowOnlyOne,
2. toggle toobar with laterally button.
Thanks!
HI Bofy,
I think this site has a great example of that:
http://ryan.rawswift.com/2009/02/15/fixed-that-bar-at-the-bottom-like-facebook/
Allen
I need a code for the user to be only able to view one div like the last example you have published but with the difference that when he clicks for the second time on the collapse button the corresponding div will be hidden. so no divs appear.. please some help!
Regarding the demo that uses images instead of the Expand/Collapse text. The div is open to start, so going to a page with this on, it is already open, clicking minus button would close.
How would i change the code, so by default the contentdiv is closed, and you would click the image to open.
I am using this with gravity forms. I want it so their is a buy-now button on the page, clicking it will make the gravity form appear underneath. At the moment, the form appears on the page by default, clicking the button hides the form. So basically it is doing the opposite of what i want it to do. What part of the javascript would i change ?
Hi Jon,
In this case you would just have the styling for contentdiv to be set to “display: none;” instead of “display: block;”.
Allen
Wow. These scripts are great! I’m using the last example (ShowOnlyOne). I’ve looked through all the posts above and can’t find a solution to my problem:
When you click on a link, I want two DIVS (each with different ID’s) to appear, and all other DIVS to turn off.
An alternative would be to somehow specify (by ID) in the link exactly which DIV’s to turn off and which ones to turn on.
Any help would be hugely appreciated.
Hi,
I have two tables in div tag, i want only one to be displayed at time which i know how to do it but what i want is it should be displayed in the same place as the first one. So if i hide first table and display second table it displays below the first table though first table is not visible.
So i want second table to take the place of the first table.
Thanks
Hi Kate,
If you use “display: none;” for your tables, it should not take up space in the layout which is what happens when you use “visibility: hidden;”.
Allen
Please excuse me if this has already been answered, but I didn’t want to read through all the replies. =P
I’m currently using your toggle5 (showonlyone) code, and have it set up and working perfectly.
However, I was wondering if it was at all possible to have the code set up so that I could close the open div by clicking its’ link again. I’m not at all fluent in JavaScript, and every attempt I’ve made thus far has backfired horribly. =P
Thanks in advance,
Paul
A few others have asked whether you can use both text and images together – is that possible. For example I’d like to create a link and then have a open/close icon next to that text link. The problem is at the moment if you use toggle5 then the text next to the image link disappears after you’ve clicked the link once.
Hi Al,
It is certainly possible to have images and text together. If you keep the text outside of the div (or whatever container) that you are using for the image that makes it appear and disappear, it should work.
This is basically what I am doing in my example for toggle5 where the text is outside of the “imageDivLink” id element.
Let me know if I am misunderstanding your request.
Allen
Thanks for the great scripts!
I decided on using the showonlyone version and it is perfect except for 1 thing. Is it possible to add a function to make it so that you can expand AND collapse the hidden div? The way it is now the last expanded div stays open with no way to collapse/hide it.
how to make div show and hide without javascript.
Hi Vijay,
Why not use JavaScript to do it? I can’t imaging having to use server-side resources to alter the display of the client. This should definitely be handled via JavaScript. Is there a reason why you don’t want or can’t use JavaScript?
Allen
Hello,
I am trying to use javascript to validate a form and display divs telling the user if they miss a field out out that is required.
I have managed to get this working however I cant make it remove the div if the user fills out the required field and then re-submits the form.
Any ideas? I can post some code if you like.
Thanks very much for any input, it is much appreciated!
Kind regards, Mike
Many thanks!! ShowOnlyOne saved my day!
Hey there, this is super helpful but I have one question. I’m helping someone out with a site and the sidebar tends to be a bit long. I thought the “Show only One” div would be perfect, and it does work, EXCEPT when you first get to the page, it shows all of them! Is there any way to fix it so it shows one or none straight off?
Link-> http://www.newleaf.inlunae.com
Hi Kel,
Two easy options are to directly enter the styling in the div via inline CSS or address it in your CSS page (recommended method) to be displayed or not by default.
One way is to address this in your CSS page:
#mydiv { display: none; }Or you can address it via CSS inline styling directly in your HTML:
<div id="mydiv" style="display: none;">my cool div</div>I hope this helps.
Allen
Here is the only way I’ve found to:
* Toggle Multiple Div with identical ID’s , using the same link
function showhide(id) {var tags = document.getElementsByTagName(‘div’);for (var i = 0; i < tags.length; i++) {if (tags[i].id == id) {tags[i].style.display = (tags[i].style.display == 'none') ? '':'none';}}}
* using this to call it:
(a onclick="showhide('show');return false;")Show/Hide(/a)
- i.e. – ’show’ is the id of the div’s
Can you show me the javascript and html to use the “showonlyone” concept but have the link text/image change like it does in the first demo – with the plus/minus sign?
Thank you so much. Your code did help me really.
I’m trying to figure out how to do this with links in wordpress.
I’m struggling with the fact that I’m forced to use classes rather than ids. I’ve done some funky workarounds though, as you can see on the “Links” thing :) (hover over an arrow)
Is there a better way than making the font 0pt and white and the div 0px high, then making the div height relative and text black and 8pt? haha
Hi there. Thanks for the lesson. I’m wondering if you can also advise on how to make a “show all” and “hide all” toggle function for multiple DIVs. What I find now is that the toggle3 function switches all of them, making any that are displaying into hidden, and any hidden into displaying. (Hope I’m making sense!)
Mil gracias.
Hello
Is it possible so that the div closes from right to left rather than top to bottom?
Thanks
Mark
[...] read an article by randomsnippets.com about showing and hiding a DIV using javascript. Although there were some [...]
thank you for a great set of scripts.
i am using the showonlyone version, and am having trouble with one small aspect. i would like to change the style of the inactive toggles, as in a different bg color or such. can you show me an example? everything i have tried has no effect or breaks the function.
Thank You in advance.
[...] http://www.randomsnippets.com/2008/02/12/how-to-hide-and-show-your-div/ http://www.dhtmlgoodies.com/scripts/show-hide-content-slide/show-hide-content-slide.html [...]
Is there any way to control both an image and text i.e. I’d like a + icon with open and then once open I’d like this to change to a – icon and close. Thanks in advance for your help.
Hi, Im in a real bind.
I used the toggle5 demo. I have it working good using divs. However I now need to add another function to cycle through the divs. Basically a way to use previous and Next function while hiding the other divs. Please help!! I would really appreciate it. Thanks so much.
Thank you for your work .
Function “show only” is very useful , whith a fade , it will be top for lighter prog .
Thank’s
Thanks for the post. Exactly what I needed!