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.
Hi Allen,
Thanks a lot for the javascript examples above.It helped me a lot.But one question i have been trying the same example using the Plus and minus images in different browsers.But the image doesn’t seem to be toggling.i have placed the code below
HTML Code :
<div id="”>
<a id="imageDivLink" entity="” href=”javascript:toggle5(”, ‘imageDivLink’);”><img src='/images/plus.gif’/>
JavaScript :
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='/images/plus.gif’>” + ctrl.getAttribute(“entity”);
}
else {
ele.style.display = “block”;
imageEle.innerHTML = “<img src='/images/minus.gif’>” + ctrl.getAttribute(“entity”);
}
}
HTML Code :
JavaScript :
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 = “” + ctrl.getAttribute(“entity”);
}
else {
ele.style.display = “block”;
imageEle.innerHTML = “” + ctrl.getAttribute(“entity”);
}
}
Hello Allen I am having trouble getting multiple of your tutorial working.. when I have 2 or more triggers, and I click on any of them the 1st one triggers. The only thing is that I am going to be having a dynamic site and I want it to just know that I am clicking on a specific button and have that one show. If you could help me I would appreciate it so much!
What exactly does newbox.length mean?
In detail would be much appreciated.
Thanks!
Hi MrThomas,
newboxesis the set elements in an array that is returned by the.getElementsByClassName()function. The.lengthproperty will return the number of elements of an array sonewboxes.lengthis simply the number of elements that is matched by class name.I hope that answers your question.
Allen
Yes! Thanks I actually came to that conclusion last night doing a little “fiddling.”
So if I am thinking this out correctly. The for loop will continuously run when you click on one of the toggles until all of the divs get met with one of the “if”, or “else” statements. And that would be 6 divs each time.
Does that make sense or do I need to rethink this?
Btw, I have to thank you for being such a great help!
Btw, i was talking about the last example on this page, so it would be the .getElementByTagName()
Allen:
The example of “only one div is displayed at any one time” was exactly what I was looking to build for a website I was designing. Thank you! I had a small tweek that I would love your input on, but I am unsure on how to edit what you already created. The edit would be when the page is first loaded the DIV#1, DIV#2, and DIV#3 are not displayed at all, only when clicking the specific toggle link would the DIV text display in the same fashion of one at a time.
Hi Matt,
If you want all your divs to not be displayed on the initial load, you can simply give them a class and the following in your CSS:
Allen
O geez, and I thought it would be javascript base. I feel silly. Thank you!
Tried it and it isn’t working. If you can make this work I will buy you some coffee! Peets.com style~!
http://tinyurl.com/cw5jsks
I tried it out and it appears to be working for me. All 3 divs are showing after it is finished loading. Then it just shows the selected one when you starting clicking on the icons. Is that what you are trying to accomplish?
Allen
I found an error with your body load statement. Many of your arguments are missing the left single quote:
As you can see the
Images/Rollover_03.pngis missing the left single. This goes on for most of the arguments you have in that listAllen
Allen – it works great, but the html in the ‘only one’ examples, either on this page or on your newer jQuery page, doesn’t validate because the divs are named (e.g. div name=”newboxes”). Divs shouldn’t be named. Is there a workaround?
Hi Russ,
Yes, instead of using the “name” attribute, you can use the “class” attribute =) I would definitely combine this with the jQuery example though because it will be much simpler and elegant.
Allen
Thanks Allen, but I’m not sure I understand – swapping ‘name’ for ‘class’ in the html upsets alignment with the script, and I’ve tried tinkering with the script, but to no avail. Could you give an example substitute script which avoids ‘name’?
Russ
P.S. I agree about the JQuery route being simpler, but I’d like to get my head around this page’s examples first.
Hi Russ,
Here is an example:
HTML code:
<table> <tr> <td> <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px;"> <a id="myHeader1" href="javascript:showonlyone('newboxes1');" rel="nofollow">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');" rel="nofollow">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');" rel="nofollow">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>JavaScript code:
Here is a working example of the code:
http://jsfiddle.net/Fh7YA/7/
I have even edited the post with this code as it is actually a bit more efficient.
I hope this helps.
Allen
Allen – thanks for new shortened script – works fine, but (arrgghhh!) not in Internet Explorer. (“Object doesn’t support this property or method.”)
Yikes! I’ll roll back the post. I honestly think the best way to go about this is to use jQuery which should take care of the browser compatibility issues.
Allen
How to hide, show, or toggle your div http://t.co/c4TfUPqF
Thank You Thank You Thank You!! After hours of searching the web and multiple failed JS Attempts. Tons of bulky code. Your simple code took only a few minutes to implement and it is exactly what I needed!! Thank You!!!!!
You’re Welcome You’re Welcome You’re Welcome! =)
Allen
hi.. I’m working on a project and it involves hiding and showing many div’s
i have tried you method and i can say it works for the most part but i do have bugs.
the div’s that I’m trying to show are all animated with JS them selves so its creating a conflict with this method.
long story short, I’m willing to pay $$ if this problem could be fixed.
please let me know if you’re interested …
thanks in advance.
Hi Mike,
I can definitely take a look at your issue. Can you give me a link to the page with the problem?
Allen
OH MAN THANK YOU SO MUCH, I’ve been looking for a simplistic way to display only one div at a time for almost a week now.
No problem =)
[...] jQuery – more and less Hide a DIV – Real's Javascript How-to Show hide content with sliding effect How to hide, show, or toggle your div Show and Hide Blocks of Text (or Images) with CSS and JavaScript – Toggle DIV Visibility – [...]
Hello,
Thank you very much for everything. Ofcourse I bookmarked this! :)
What i was searching for, and sadly i didn’t found it, is a script for a menu:
- with 6 buttons that links to div’s that slides/toggles (slow) in when clicked.
- Standard is div id=1 open. But has to close when one of the other buttons is clicked
- when any other button is clicked, the other div’s has to close.
if there is a chance you can help me, that would be great! :)
Greetings, Jos
I see you allready got something like that explained..:)
http://www.randomsnippets.com/2011/04/10/how-to-hide-show-or-toggle-your-div-with-jquery/
But still wondering what happens if the Div is on the same place.. Now the collapse and expanding happens on the same time, right?
Greetings, Jos
Works Great! Thank you!
Hi, great work man.
I have this project where I want to display a divs in progress like Toggle4 but in add I would like to do shortcuts to them. I can do counter = 20 in the onclick attr but if I do that jump, counter keeps going higher with the counter++ dir but it doesn’t show the divs 21,22 etc. Is there a way to do that?
That would be so helpful and web much more interactive :)
Thanks a lot for this magic
Hi, first off, thank you so much for these examples and tutorials. They’re a big help-especially after scouring the internet for other ways to display this content I’m putting in collapsible elements.
That being said, what I’m ultimately going for is something that will allow me to hide different content in the exact same space. The last example you have here is the closest thing I have found to what I want.
The only problem is that I’m trying to make it so that the content hidden in each div will appear below the other div “headers” when toggled. Perhaps if you view the test page I have up on our testing domain you will see what I’m trying to do.
I feel kind of dumb as if I should be able to figure this out myself, as I’m working on it, but nothing I can come up with is working. Essentially these things are going to kind of work like collapsible tabs. The content will ideally be hidden until clicked on, and only one will be displayed at a time. It’s just the problem with the width exceeding the narrow vertical space.
You might first see that the web page looks kind of janky because the content has slid underneath other content. If you close the first toggle button it will look as it’s supposed to. After closing the first open toggle you will see 3 other buttons right above the toggle buttons. Those are what I would like to have be the toggle switches, with different price tables underneath each one when clicked on. An example of a price table is under the first toggle div.
If you have any idea how to keep the other divs on top of the content of each hidden div while only still displaying one at a time, please let me know. Thanks!
(I hope that wasn’t too confusing, I was trying to be thorough.)
Doh, nevermind, I figured it out. It was as simple as moving all of the divs into 1 and putting on a colspan=”3″. I do feel kind of dumb now.
If you’d like, I will have it up and working by today or tomorrow and you can look at it at: http://www.totallyweddingkoozies.com
Thanks again for your helpful code!
I am using Toggle5 with the images and I cannot figure out how to get it to open the correct + when you click on it. In its current form it always opens the first one no matter where you click:
http://www.neurosolutions.com/products/course/online-course-faq.html
Appreciate your help!
Can delete. I ended up figuring it out. Thanks for the great tutorials though!
Sorry for the delayed response. I was on vacation and just got back. I’m glad you were able to figure it out though! =)
Allen
Hi im trying to use the demo titled “Here is a new demo in response to a request where only one div is displayed at any one time.” now i have it working but the buttons are in the middle and shift up to allow the information to be seen, how do i make it so they stay inplace and the information slides down? Like it does in the demo.. Thanks
Hi Louisa,
This most likely has to do with the CSS of the elements surrounding your divs. Do you happen to have a url that you can share?
Allen
You can find my page at http://www.louisagibbons.com/waiheke.html i have just put it up there to demonstrate to you so the pics and links aren’t working. but the toogle does
Nevermind i figured it out, needed a tr vertical align.
Hello, is this script working with Chrome? I am having it work on Firefox but not with Chrome, where the div will not hide..
Hi Fabio,
The scripts should work fine with Chrome. You can test it yourself by opening up the tutorial page in Chrome.
Allen
When I implement the showonlyone or showonlyonev2 code, my site displays all the hide/reveal content at once when it first loads in a browser. Once I click an option it shows only one.
I have the hide/reveal content all in one spot where I’d like content to toggle to the left of a set of options. Is there a way I can set it up to show only one hide/reveal content item or none at all on page load?
Hi Erin,
You can easily hide the content of your divs on page load via CSS. Here is an example:
<table> <tr> <td> <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px;"> <a id="myHeader1" href="javascript:showonlyone('newboxes1');" rel="nofollow">collapse</a> </div> <div name="newboxes" id="newboxes1" style="border: 1px solid black; background-color: #CCCCCC; display: none; padding: 5px;">Div #1</div> </td> <td> <div style="border: 1px solid blue; background-color: #99CCFF; display: none; padding: 5px;"> <a id="myHeader2" href="javascript:showonlyone('newboxes2');" rel="nofollow">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; display: none; padding: 5px;"> <a id="myHeader3" href="javascript:showonlyone('newboxes3');" rel="nofollow">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>In this example, you can see from the inline CSS that I have set the display attribute equal to “none”. You can choose whichever you would like to show on page load by changing this value to “block”.
I hope this helps.
Allen
Thank you! I had changed the CSS attributes and missed that. Fantastic tutorial, thanks so much for sharing!
One more question!
I’m doing w3c validation, and in line 4 below ( for(var x=0; x<Q.length; x++) { ) it says the semicolon isn't allowed.
I tried removing it, and of course the script no longer works. Is there something I can do to make this pass w3c validation?
Thanks again!
function question(clicked) {
var Q = document.getElementsByTagName(“div”);
for(var x=0; x<Q.length; x++) {
name = Q[x].getAttribute("name");
if (name == 'Q') {
if (Q[x].id == clicked) {
if (Q[x].style.display == 'block') {
Q[x].style.display = 'none';
}
else {
Q[x].style.display = 'block';
}
}else {
Q[x].style.display = 'none';
}
}
}
}
2 more errors! :(
Error Line 61, Column 30: element “q.length” undefined (this is another semicolon issue, I think).
for(var x=0; x<q.length; x++) {
and
Line 61, Column 21: start tag was here (it's looking at the "<" between x and q)
for(var x=0; x<q.length; x++) {
Awesome article………its exactly what i wanted!!!! it helped me a lot!!!Thank you!!
You’re welcome =)
I have one problem statement, please provide the solution
- i am controlling the functionality to hide and show the div’s on initialize.IF i want to display all div’s it will be displayed as collpased.
- in case i am hiding one or two of the div,the div’s that are on screen should move up and would occupy it’s space.
- in case if i get all the screen in collapsed mode.i can expand it on click.Expand button for each will be different for every div.
I think it will be easy to implement using jquery functions.But do we have a logic to auto adjust the div’s in javascript.
Hi Sandeep,
I apologize but I don’t understand what you are trying to do on your site. Do you have a sample page that I could look at to see what you have so far or your existing JavaScript code?
Allen
Thanks allen for the response.
The problem i am facing is with auto-adjustment of my group boxes. I have 3 group boxes on the screen. But depending on the logic we are hiding or displaying it.So in case i am not displaying the first group box. I want my other 2 gruop boxes to shift upwards and takes space of first’s place. I can do that through hard coded pixels but it would be a static approach and there can be browser compatibility issue .i want a solution where we can adjust the hight from top without using hard coded pixels.
jQuery UI “Accordion” approach is somewhat i want to implement through java script. But with one minor change
- i don’t want to collapse other div’s when i am expanding one.I want to show all expanded,after clicking one by one on all the div’s.
Link :http://docs.jquery.com/UI/Accordion
Hi Sandeep,
If you want to allow multiple divs to be opened, then you shouldn’t use accordion. There is a notice in the link you gave to me and a snippet of code already there that shows you how to accomplish this.
Allen
Allen ,as i already mentioned that we can have a solution through jquery. But i want to know if there is any logic where we can auto adjust the height or we say expanding/collapsing in java script avoiding hard coded pixels.
Hi, i have more common question.
I need to start the js after i open new page. So it will be a href link which opens new page, and then automatically needed to run the js to show up the div. Is it possible at all? Like i click in parent page and then shows up the div in next page, which is not visible by default. can you help me?
Hi guntars,
Yes, it is. I have been receiving a lot of similar requests so I do plan to make a demo/tutorial for it. I hope you can hold out for a bit. It will be a PHP/JavaScript solution though.
Allen
Hi guntars,
I have just finished the new tutorial. Here it is: http://www.randomsnippets.com/2011/10/09/how-to-hide-or-show-content-based-on-links-or-urls-via-javascriptjquery/
It is pure JavaScript/jQuery so there is no server-side scripting going on =)
Allen
hey, thanks. Yes i can hold, but just if you can give me approx time when you can think about this?
Hey Guntars,
I’ve already responded with the new post about a week ago. Here it is again: http://www.randomsnippets.com/2011/10/09/how-to-hide-or-show-content-based-on-links-or-urls-via-javascriptjquery/
Allen
Hi, thanks for the fine article. I’m new to java as many others & here I need your help.
I’m using wordpress short codes on wp page to show the title and excerpt of top 5 posts from a category. I want my users to click the ‘+’ button (image) at the left side of the title to read excerpt (small note) about it.
I added your java code and it is working but with the only 1st title. The remaining 4 are on their place with excerpt as they were. Is it possible to add this ‘+’ button to the left side of the remaining titles and connect it with their excerpts, if yes then how?
Here is the link : http://worldocricket.com/?page_id=7462
Hope I’ll get some help.
Hi Rehan,
The link you posted appears to be broken. I get the following message:
===
Not Found
The page you are looking is not here..
===
Allen
Hi I want to combine the first and the last demo. Just want [code]text.innerHTML = "show";[/code]
and
[code]text.innerHTML = "hide";[/code]
in the last demo, but I can’t get it to work.
Thanks in advantage, Joeri
Hi Joeri,
It sounds like you did not correctly select the DOM element for “text”. I would check that first:
I would hardcode the “idOfElement” directly and see if you the text changes.
Here is a sample of what the HTML looks like:
If this does not work, I would changed the name of “text” because you may be having a naming collision.
Allen
Hi Allen,
Thanks for your reply. I’ve tried your solution but it won’t work the way I want it. This is my code:
Untitled Document
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';
text.innerHTML = "show";
}
}else {
newboxes[x].style.display = 'none';
}
}
}
}
And I want to have myHeader1-2 and myHeader2-2 another background when they are ‘activated’. Hope you have a solution for me.
Thanks, Joeri
Hi Joeri,
I have a working version here but I am unclear as to what you want to do. Maybe you can edit the HTML a bit and I’ll have a much better idea of what you want to do.
http://jsfiddle.net/aaMNw/14/
Allen
Hi Allen,
Thanks for your quick anwser. I’ve edited your code a bit so you can have a better view on what I want.
the script:
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';
}
}
}
}
The HTML:
1
2
show 1
show 2
So, I want that the text ‘show 1′ and ‘show 2′ change in ‘hide 1′ ‘hide 2′ when active. I Hope you understand my bad English :).
Joeri
HTML don’t work so here’s the link:
http://jsfiddle.net/aaMNw/24/
sorry for the unnecessary posts.
Ok..I think I get it now. Here you go =)
http://jsfiddle.net/aaMNw/33/
Yes thanks, but I found a ‘bug’. When you show one it springs to ‘hide’ but if you click then the other one it stays on ‘hide’, I don’t know how to fix it :(. Thanks for helping so far.
Joeri
Ah yes! Ok here is another revision:
http://jsfiddle.net/aaMNw/35/
It is not the prettiest code snippet but it works (I think).
Allen
Thank you ever much, it works like a charm!
When I used the Toggle 4 script (Multiple divs – one button) in a web page form, it tries to submit the form. Is there a way to stop this action?
Hi Jim,
Try one of the following suggestions:
I would try the top suggestion first. Let me know how this works out for you.
Allen
Quite easy the final solution:
$equip:
$temp°C
Thanks Luis for the solution. I think your code may have been removed. Please try again using “pre” tags which should preserve your code.
Allen
Let’s say that I have a few different links. Next to it I have a few different nested div layers. When I click on one of the links I want it to display one specific div and hiding all the other ones. Once clicked on another link it makes the corresponding div layer visible and toggles off the other ones. Basically each link makes one corresponding div visible and hide the other ones. All these would be class based.
Question is, how do I script that?
Thank you so much
apprecaite the help,used it and it worked magic,going to put your site on my project as a form of appreciassion
Sweet =) Thanks!
Hello everybody,
i have a rectangular main image with small divisions betweens colors gradient and i´m trying to display just part of this image depending of a gathered value. Basicly is a “purple to red” bargraph image that represent temperatures from 0ºC to 100ºC, so if the local temperature is about 32ºC, my DIV must show only firts 32 pieces of the main image. This is a huge challanger to me! – Any idea?
Hi!
Im working on a website. I used your showonlyone code. When I literally just copies the html and javascript, when you open the page the first box is automatically there.
So I applied the codes. In the html code, you put the styles on the html div. I adjusted mine and put the styles on the css code. I didn’t touch or edit any javascript. I just remove the styles in the div and put it on css. Now when I open the page, The first box wont appear, I need to click it first.
Any suggestions? I need/want that the first box will show when you load the page.
Thanks!
And great tutorial! Easy and straight to the point.
-M
It sounds like the CSS for the first box is not set to “display: block;”
I would first try inline CSS to style that first box directly to test it out.
Hope that helps.
Allen
Thank you. It worked Chief!: )
Hey There,
i have tried using your script for i have however tried using hotspots of an image to link instead of tags,
The problem i have is that when the intitial page is loaded ALL divs are displaying, instead of just the 1
here is a link
http://socialportrait.net/clients/marcoPolo/mpPage.html
Hi Ignacio,
I just took a look at your page and it looks like only the first one is showing so it looks like you have addressed the issue.
Allen
Hi Allen,
I’m working on my own site (mostly joomla-based) and would like to use your spoilers script to reduce info clutter on some pages. However, I’m not entirely sure how to “install” this script since I’m not an advanced coder or web designer. I know I’ll need to install it using FTP, but I’m not exactly sure on how to go about it (my site is not up yet but my hosting provider has given a pretty decent template for me to work on). Appreciate if you can help me out!
Hi Ahmad,
Sorry for the late reply. I’ve been crazy busy lately. Unfortunately it would not be easy for me to help you in this case. You would need to incorporate the JavaScript code into your theme somehow so that it automatically loads. If you want the JavaScript code to load only for specific posts, it may become even trickier. It’s been 4+ years since I have used Joomla so unfortunately I will not be of much help to you. Sorry.
Allen
Actually, I just found this:
http://www.joomlablogger.net/joomla-tips/joomla-templates/how-to-easily-add-javascript-snippets-to-joomla/
I think this will point you in the right direction.
Allen
Hi Allen,
Many thanks for the link – will try it out! :D
Hi, I changed everything you said, But now It is still acting weirdly :/
Would you mind quickly taking another look?
Sorry to bother you so much, I am completely new to Javascript..
Thanks so much!!
When you render the page, the advertisement block is still not registering as “display: block;” and I think it is because you have float in there as well which is conflicting with each other.
Try removing the “display: block;” from your CSS.
Then I think we will need to reverse the toggle if/else statement to check whether it is none instead:
That should do it!
Allen
Hi, Great tutorial!! Thanks!
Just a quick question, Is it possible to hide a div, then the page re-adjusts and centre’s the content div.. The div that I want to hide is a side bar, Its on the right hand side of the content??
Thanks!
Hi Harrison,
Thanks! Yes, you can change the CSS properties of an element dynamically using JavaScript. Here is some sample code to work with:
Please note I used an arbitrary number for the top and bottom margins to be 10px but the important one is the “auto” value which is used to center your div.
I hope this helps.
Allen
Thanks, Worked a charm!
How can I change it so that there are different variables, e.g. Margin left 10% Margin top 30px Margin right 10%??? Thanks Again!
Also, How do I make it that it changes back when it toggles?? Right now it is working, But when I toggle back. The centrecontentdiv is still centred?
I hope you can make sense of that :D
Sweet! If you want to indicate each margin, just pass 4 variables over:
The order is top, right, bottom, and left. I set the bottom to zero so replace that if you have an actual value you would like to use.
Allen
Its me again! – Would you mind taking a look at my site? http://www.brisbanelongboarding.com
and try to tell me what the problem is? Thanks!
You are a legend!
I am assuming you want to hide the sidebar and center your main content div when the user clicks on “Toggle Bar”.
If so, to make things simpler, I would place your header and container divs into one main div:
<div id="mainDiv"> <div id="header"> your header content...</div> <div id="container"> your container content...</div> </div>This way, you only need to center just the mainDiv content and that will take care of all the child elements like your header and container.
The main issue is that your advertisement div is not a block element and instead you have it floating. If you have CSS styling for your advertisement to be “display: block;” this would all work.
Allen
Hi I think this is brilliant, but I have one problem with toggle 5 in that it works perfectly in Chrome, Safari, and on an android mobile device, but I can’t get it to work on either a iphone 3gs or iphone 4 – does anyone have any experience of this. I am urgently trying to develop a cross platform html5 app using JqTouch. Many thanks
Hi Derek,
It appears to work for me on an iPhone4. Are you referring to the demo that uses the + and – icons to toggle the div? If so, that is the one I have confirmed to be working properly.
Allen
Hey man… look this help me alot… but can you answer a question that i can’t find the answer..
How do i change the content that is inside of a iframe?
like the iframe has an id called (play), and inside of the iframe as another id called(imageson).
how do i change the imageson id to none?
Thanks
Hi Jack,
I found this that might address your question:
http://xkr.us/articles/dom/iframe-document/
Allen
Its very nice and Very easy to apply for any place
thank u very much…..
Hi allen i made this function:
function fishing(showHideVideo,showImages,hideImages) {
var video = document.getElementById(showHideVideo);
var imageshow = document.getElementById(showImages);
var imageshide = document.getElementById(hideImages);
if(video.style.display == “block”) {
video.style.display = “none”;
imageshow.style.display = “block”;
}
else {
video.style.display = “block”;
imageshide.style.display = “none”;
}
}
what i want to do is… click on the image (“something”) and only does this: hide the image “something” and show the video…
And the in the second image (“something2″) only does this: hide the video and show the image “something”…
I made the imageshow and imagehide, so it’s done, because one only hides, and the other only shows’s… but how do i put a videoshow and a videohide, that one only hides and the other only shows?
I tried this but didn’t work:
function fishing(showVideo,hideVideo,showImages,hideImages) {
var videoshow = document.getElementById(showVideo);
var videohide = document.getElementById(hideVideo);
var imageshow = document.getElementById(showImages);
var imageshide = document.getElementById(hideImages);
if(videohide.style.display == “block”) {
videohide.style.display = “none”;
imageshow.style.display = “block”;
}
else {
videoshow.style.display = “block”;
imageshide.style.display = “none”;
}
}
Can you help me?
Hi Dean,
Do you happen to have a link to the URL for me to visually see what you are trying to do with this?
Allen
Hi Allen, remember David and hist problem with getting class?
Well he told me… and i said, don’t need to bother him…
Days latter I thought of something so simple…
I don’t know why but doesn’t exist document.getelementsbyClass () well exist but creates lot’s of problems and mess… so i remeber, if this only search for id’s well… i want to remove all the icons (class canal) inside of the id canais… so i just create and id (id =”icons”) exacly like id canais inside of him, then i put the icons inside of “icons” id and say to hide and does the same but with and Id…
That’s anyway for all your help Allen, you have a knowledge that i wish to know…
PS: Congrats for the new look of this site :)
Hi Peter,
I’m glad you were able to resolve your issue by using ID. Technically IDs are supposed to be unique but if it works and it is cross-browser compatible, I say go for it! :)
Thanks for the compliment on the new theme. It is the standard WordPress 2011 theme which is BEAUTIFUL and elegant.
Allen
Hi Everyone,
I want to grayout the background when a modal comes on page load..Can anyone help me out on this.How can i code for this in javascript.Thanks alot in advance!!
Hi Barnali,
To do the modal on page load, it will require JavaScript and CSS. I found a nice modal tutorial on this and the CSS. If you are using jQuery and the jQuery UI library, it already has some nice built-in dialogs and modals.
I hope this helps.
Allen
thanks alot @ax163.
Good Evening Allen.
Trust all well on your side of the world.
Im not that clued up on coding, well more like advanced coding like java script.
Im wondering if you can help me out here.
Im trying to, lets say”fancybox” a bunch of videos. The show and hide div function, would it work for this type of project? I have a few thumbnails of the vids and when u click on the thumb nail, would it at all be possible to have an iframe of the youtube vid come up (almost like the fancybox script)?
If i view this project off line, it works like a bomb (fancybox) brings up the vid and plays awesomely.( the vids arn’t in iframe as i have copies on my hard drive) But doesnt work when i upload it to the site. ??? It there anything i can do or u can suggest for me to have this effect on my site?
Best regards
Hi Brendan,
I think I understand your issue but can you give me the url to your site? I would be much easier for me to see what the issue is and possibly give you a solution.
Allen
Hi Allen,
Thanx so much for the speedy feed back!!!
Here is the link the my site http://rstfitness.co.za/.
If u look at the bottom of the home page u will see what im trying to do. :)
Hi Brendan,
The reason why the videos do not work is simply because the “John Smit is back in action__ Ready to take on 2011__.flv” is not there. I am getting a 404:
“NetworkError: 404 Not Found – http://rstfitness.co.za/video/John%20Smit%20is%20back%20in%20action__%20Ready%20to%20take%20on%202011__.flv”
Are you sure the following exists in your directory?
http://rstfitness.co.za/video/John Smit is back in action__ Ready to take on 2011__.flv”
I would be careful of having spaces in your file name and replace them with dashes. They can definitely cause some problems depending on your environment.
Also, it may be worth looking into nice jQuery video gallery plugins to do the job. Here are some examples:
http://www.videolightbox.com/#preview
http://smple.com/videoGallery/ (You can easily customize the links with your images to make it look nice.)
I hope this information helps!
Allen
Hi Allen,
Thanx once again for your feed back, its highly appreciated:)
im going to use the videolightbox plugin and see if this does the job.
Ill be sure to post my findings and achievements here once im done.
Thanx Allen
Bean
No problem. I hope it works out for you.
Allen
Hi Allen,
Thanx for the links. they works perfectly :)
Sweet! =) It looks like you went with the jQuery solution. Awesome choice! I would have done the same thing.
Allen
ahhaah thanx again Allen. Just a lil pro tho, once one of the vids are viewed, the site stops? like u cant view another one?
But yeah man, once again thanx for saving me on this one lol :)
It looks like you are getting a ton of JavaScript errors that are repeating:
swfobject.removeSWF is not a functionhttp://rstfitness.co.za/cprimvid/engine/js/videolightbox.js
Line 1
Did you customize the
videolightbox.jsfile?Allen, as i said im not too clued up with the script side yet. and no i havent edited the.js file. should i?
Hi Allen,
Sorry budd, i forgot to take out the old script for the swf i had in preivously.. All is 100s now.. thanx again man
Awesome. It’s looking good!
Hi Brendan,
I think building an e-commerce page/site from scratch is not the most efficient way to go about accomplishing this. You’re basically reinventing the wheel. I would recommend installing the WordPress content management system and using the WP e-Commerce plug-in. You can literally have this up and running in about 10 minutes. It supports many of the popular payment gateways, including PayPal and Google Checkout, and transactions are made safely through SSL connections.
In addition, you have tons of free e-commerce themes that you can use and customize to your own liking.
Here is a how-to video where the guy installs everything in 5 minutes.
Allen
Hi Allen,
Trust u are well.
Thanx for the guidance on the e-commerce, i didnt go with the word press, instead i went with joomla :) http:/rstfitness.co.za/products :)
need more guidance!
Iv done an email signature for my client http://www.rstfitness.co.za/sign/ (this is my coding) What i need Allen is to somehow find a way to force these images to show in the emails WITHOUT other people having to “click here to view images” in the mail when its received. The signature works perfect, even the links work, but i need them to show in the email on the recipient mail without asking to display them. IS THIS AT ALL POSSIBLE.
Thanks Allen.
Bean
Bean, that would be a dream come true for all the marketers out there =) Unfortunately, you have absolutely no control over that. Depending on the email client, it has to be specifically approved by the receiver to be a trusted source. I would recommend to keep the images near the bottom of the email so that the text appears above the fold in the email previews. Otherwise, users will just see the broken image links and the chance of them reading your email or even clicking into the clicking will be very low.
Allen
No, it is not recommended for you to edit library files directly.
Hi Allen.
Just wanna say thanx again for helping me out. My client is very very impressed : )
Im still new to all the coding we have in our computers these days, iv only been a web designer now for 2 years, learning new things everyday.
I have no idea about forms and php and stuff. What i need to do for the same client is make a product purches form.
Iv search the internet and only get simple forms. What i need is a form that i can modify in the future as more products come up. If u go the order form http://rstfitness.co.za/order/form.php everything here is perfect, im just missing one thing. ok well two things.
the quantity and total. Say now someone wants 3 of this product and then wants 10 of the next one, the clients wants it totaled and sent to the mailing address. So this is my problem, i dont know where to look or what to do to get the function there. It seems ur pretty clued up with scripts and stuff.
What can u suggest?
thanx Allen, yeah been searching and searching lol hahaha, just needed to hear it from u to be dead certain. Thanx again :)
Great tutorial! I am using the at any one time code and was wondering if you knew a way to use a image as the button. When the button is clicked it would change images.
Example(when page is loaded):
Collapse 1btn(green img) Collapse 2btn(blue img) Collapse 3btn(blue img)
Example(when Collapse 2btn is clicked):
Collapse 1btn(blue img) Collapse 2btn(green img) Collapse 3btn(blue img)
Any suggestions would be greatly appreciated.
Hi Joe,
You can style a tags to look exactly like buttons with the right CSS and still get the same effect as an actual button =)
Here is an awesome example!
Allen
Perfect Thanks!
Hi there – I’m working on my website and company’s social networking and I find it difficult to organize them all. Can you direct me to how you would go about having a social bar at the bottom of the page (like I have it) but with the ease of clicking the button to (for instance) +1 with google, +1 like with FB, tweet with twitter etc. much like you have it on this page just above this reply.
Thanks for your help. It’s taking me way to long to find something I like!
Have an excellent day.
Rob
Hi Rob,
I used a WordPress plugin for the nice buttons =)
It is open source so you should be able to see the PHP/HTML/CSS/JavaScript code to implement it. You may want to reference the author though to at least give him/her credit for the awesome work.
Allen
Tell you this… my friend who owns the site is gonna email you with the e-mail [censored] because the website is not publish yet, and my friend Peter will send you the html file called “canaisindex.html”…
Hope you find the solution :)
PS: Great Post, did you learn by yourself?
just one more thing can you give me your e-mail?
PS: remove this coment if you want
Hi David,
Feel free to email me at allen.liu@randomsnippets.com.
Allen
I’ll give it my best shot. Yes, a lot of things can be learned from the internet these days =)
Allen