Random Snippets

  • Home
  • Sequence analysis blog
  • About
  • Categories
    • javascript
    • mysql
    • php
  • Subscribe via RSS

How to hide, show, or toggle your div

February 12th, 2008  |  Published in javascript  |  157 Comments

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

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

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

show <== click here

peek-a-boo

Here is the sample HTML and Javascript code:

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

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

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

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

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

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

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

collapse

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

Here is what the CSS styling looks like:


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

Here is the HTML code:

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

That's all there is to it! =)

Here is the toogle2 JavaScript function:

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

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

Demo
collapse
Div #1
collapse
Div #2
collapse
Div #3

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

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

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

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

Here is the HTML code for the demo:

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

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

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

Demo
First
Second
Third

Here is the HTML code:

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

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

Here is the JavaScript code:

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

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

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

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

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

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

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

Demo
Let's use images!

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

Here is the HTML code:

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

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

Here is the JavaScript code:

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

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

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

Demo
collapse
Div #1
collapse
Div #2
collapse
Div #3

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.

Share with a friend:
    

Customize message


[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Responses

Feed Trackback Address
  1. Joe says:

    April 20th, 2008 at 12:13 am (#)

    what if i need two links.. how to do that

    [Reply]

  2. Knix says:

    April 21st, 2008 at 10:45 pm (#)

    Hi Joe,

    If you have 2 divs that you want to hide, you just need to have different ids for each div. Here is an example:

    1
    2
    
    <a href="javascript:toggle2('toggleText1','switchText1');" rel="nofollow"><div id="switchText1">show</div></a><div id="toggleText1" style="display: none"><h1>this is my first div</h1></div>
    <a href="javascript:toggle2('toggleText2','switchText2');" rel="nofollow"><div id="switchText2">show</div></a><div id="toggleText2" style="display: none"><h1>this is my second div</h1></div>

    [Reply]

  3. ayesay says:

    July 6th, 2008 at 11:56 pm (#)

    for two toggle. need two javascript? cos elementID is not in array :(

    [Reply]

    Knix reply on July 7th, 2008 12:13 am:

    Hi ayesay,

    As per your request, I have created a third demo here. Please check it out. It handles multiple toggle elements!

    I hope this information helps.

    Thanks for your comment/question.

    [Reply]

  4. IDB says:

    July 29th, 2008 at 12:49 am (#)

    hi,

    very usefull!!

    what if i need one link, to toggle 5 div’s, one div at a time.
    1 click on the link, display the first hidden div,
    click the link again, display the second div,
    and so on till all 5 divs are displayed.
    when the fifth div is displayed, i want the link to disappear…

    thanks!

    [Reply]

    Knix reply on July 31st, 2008 9:34 pm:

    Hi IDB,

    I have created a demo in response to your request. I hope it helps =)

    [Reply]

    IDB reply on August 4th, 2008 1:50 am:

    Great! Exactly what I was looking for!!! Thanks a million!

    [Reply]

  5. Iona says:

    July 30th, 2008 at 1:57 am (#)

    Works like a charm. Thanks!!!

    [Reply]

  6. Charlie says:

    August 9th, 2008 at 2:31 am (#)

    Hi all,

    Reloading the whole page calls the content back by default. What if I don´t need the content status (none or block) to be changed by reloading the page? Would be possible?

    Thanks

    [Reply]

    Knix reply on August 9th, 2008 9:00 am:

    Hi Charlie,

    This is certainly possible via cookies which can remember a user’s settings. I have a demo based on cookies:

    http://www.randomsnippets.com/2008/04/14/how-to-dynamically-add-content-to-a-div-via-javascript/

    I will try to include a demo here which involves cookies soon.

    [Reply]

    Charlie reply on August 16th, 2008 6:40 am:

    Hi Knix,

    It would be very useful for me. Thanks in advance.

    [Reply]

  7. Jo says:

    August 11th, 2008 at 8:09 am (#)

    Hi, I’m looking for a script that only shows one div at a time…

    i.e. three divs; it starts with the first div shown, when a link is clicked the second div shows and all others are hidden, when another link is clicked the third div shows but no others. Any ideas? Thanks x

    [Reply]

  8. Dave says:

    August 25th, 2008 at 5:59 am (#)

    Hi,

    I am using an onclick on an input text box to fire a toggle on a div that is hidden via display:none. The toggle works but in a strange way. The user has to click twice (instead of once) on the input field in order for the div to display. I have search far and wide without any conclusions. I have posted my test code below if you can help.

    Thanks

    test1

    function disInvProducts()
    {
    if (InvProducts.style.display == “none”)
    {
    InvProducts.style.display = “block”;
    }
    else
    {
    InvProducts.style.display = “none”;
    }
    }

    #InvProducts { background-color: #FF33CC;
    position: absolute;
    width: 200px;
    height: 300px;
    display: none; }
    .DetailInput1 { background-color: transparent;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 8pt; }

    Products

    [Reply]

    Knix reply on August 25th, 2008 7:53 am:

    Hi Dave,

    Can you please include the HTML as well? I would like to see which input field you are referring to in this case.

    [Reply]

  9. Dave says:

    August 25th, 2008 at 8:00 am (#)

    Hey Knix,

    I actually solved the issue a few moments ago. All I did was change the toggle code around. It was nothing but logic.

    Old Code:

    function disInvProducts()
    {
    if (InvProducts.style.display == “none”)
    {
    InvProducts.style.display = “block”;
    }
    else
    {
    InvProducts.style.display = “none”;
    }
    }

    New Code:

    function disInvProducts()
    {
    if (InvProducts.style.display == “block”)
    {
    InvProducts.style.display = “none”;
    }
    else
    {
    InvProducts.style.display = “block”;
    }
    }

    Thanks for the help though.

    [Reply]

  10. Fernando says:

    August 26th, 2008 at 4:49 pm (#)

    Thanks for this helpful script. I have it working nicely. However, I want to customize it a little more. I’m using “function toggle2″ and would like to swap out your text for a “plus” and “minus” icon. For now I’m using text for the “+” and “-” signs but I would like to use images. What would the DOM syntax be for that? I’m not well versed in JavaScript so forgive my ignorance.

    Here’s what I have so far:
    …
    text.innerHTML = ” + “;
    …

    I was hoping it was something simple such as:
    …
    document.getElementById(‘imageID’).src = ‘icons_plus.gif’;
    …

    but that doesn’t work. Do you have a solution?

    Thanks in advance!
    - Fernando

    [Reply]

  11. techniqueal t. says:

    September 1st, 2008 at 11:35 am (#)

    Hi! I have a question. Your code works like magic! =) I’m just wondering how would I go about customizing the code to toggle images (ex. plus.gif and minus.gif) instead of texts (i.e. Collapse/Expand)? Thanks!

    [Reply]

    Knix reply on September 1st, 2008 1:10 pm:

    I have not tested it but you should be able to place your img tags in the innerHTML instead of the collapse/expand texts. Try this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    function toggle() {
    	var ele = document.getElementById("toggleText");
    	var text = document.getElementById("displayText");
    	if(ele.style.display == "block") {
        		ele.style.display = "none";
    		text.innerHTML = "<img src='plus.gif' alt='Expand content'>";
      	}
    	else {
    		ele.style.display = "block";
    		text.innerHTML = "<img src='minus.gif' alt='Collapse content'>";
    	}
    }

    [Reply]

  12. Hellcat says:

    October 7th, 2008 at 1:59 pm (#)

    Hi! Got this site from a friend while brainstorming over a problem for a webpage, maybe you can help me out?

    The problem I have is that 2 div blocks is in use, where one contains (named “contentleft”) a picture where 3 seperate hotspots is active, each of these hotspots are links with a mouseover funcion and are built up with polygons. The problem is that when click at the links, they open in a new tab or a new browserwindow, thats not what should happend.

    So what should happend? Well when you click at one of the hotspots the link should activate the page its linked to in the other div block, called “contentright”.

    The hotspots dont have any “names”, which would make it easier honestly, if they had, and the div blocks, well they have “names” but you cant target them. Using a sepererate css document to create the div blocks.

    No tables or iframes is wanted in this particular case.

    Hope you can help, thanks in advanced!

    Best regards Hellcat

    [Reply]

    Knix reply on October 7th, 2008 2:08 pm:

    Hi Hellcat,

    It sounds to me like you want to load html pages dynamically into your “contentright” div based on where a user clicks on your hotspots.

    If this is the case, you will need to use AJAX. I highly recommend using the jQuery library:

    http://jquery.com/

    It is very lightweight and has tons of nice plugins.

    If you would like to see a demo as to how this will work, please let me know and I will come up with a demo post on this topic.

    [Reply]

    Knix reply on October 7th, 2008 2:10 pm:

    BTW, I noticed you tried posting again with the code. Try placing your code between these tags:

    <code>
    actual code…
    </code>

    [Reply]

  13. Abdoanmes says:

    November 12th, 2008 at 5:58 am (#)

    Thanks for the great examples above! They are very helpful in creating some really cool websites. When I first came across this tutorial I couldn’t think of a way to use it for any of the projects I was working on. Finally, I was cleaning out my bookmarks and revisited your page. I was excited to see the new additions and that got me thinking about other ways to use the script. I thought that it would be nice to have a series of ‘hidden’ divs, and only one can be opened at a time. Basically, if you have a div ‘Expanded’ and click on another div, the first would close, and the selected would open. It would be possible to close all the divs, but only have one opened at a time. I tried messing with the script to produce this effect, but I’m not really sure what I’m doing due to lack of any real knowledge in javascript.

    Thanks very much for your great insight and taking the time to help everyone out, it’s very much appreciated.

    Have a great one!

    [Reply]

    Knix reply on November 15th, 2008 12:42 am:

    Hi Abdoanmes,

    Thanks for the comments! =)

    Please check out the latest demo. It addresses the issue you are facing.

    [Reply]

    Abdoanmes reply on November 15th, 2008 11:22 am:

    That’s really awesome and exactly what I was looking for. I played with it a bit and I changed the initial state of all the divs to ‘none’ so that the a visitor would have to select which div would be opened first. Now in this demo, once a div is turned on, all the divs cannot be collapsed again when you select the collapse button above the currently opened div. If I were to add another ‘else’ statement to the function, would that be the right logic to create the effect I’m looking to achieve? Or does that just throw a wrench into the works?

    Great info here, thanks!

    [Reply]

    Knix reply on November 19th, 2008 10:44 pm:

    Hi Abdoanmes,

    I do not think adding another else statement in this function will achieve what you are looking for. It will require some modification of the function but I do not have much time to work on it right now. I have a lot of catch up work to do because I was away the last couple days. Please let me know if you are able to modify the function.

  14. Justin says:

    November 19th, 2008 at 4:19 am (#)

    Hi, I’m trying to employ the technique in the last demo, but I’m having a little trouble. The div layers I’m trying to show or hide contain some big tables with image thumbnails, and the toggles seem to have no effect.

    The page’s code is pretty long, but can be found at nicholemaury.com/images.html

    Thanks for your help!

    [Reply]

    Justin reply on November 19th, 2008 4:39 am:

    Nevermind, I seem to have fixed it!

    [Reply]

  15. Justin says:

    November 19th, 2008 at 8:30 am (#)

    I just noticed that the last demo seems to work in all browsers except Internet Explorer. Why would that be?

    [Reply]

    Knix reply on November 27th, 2008 10:01 pm:

    Hi Justin,

    Thanks for letting me know. I just found out that IE does not support getElementsByName which would throw a monkey wrench in this. I will find a new way to do this but will need some time.

    [Reply]

    Bishop reply on January 22nd, 2009 10:37 am:

    This is the code I have been seacring for but I need it to work for IE as well as firefox. Is there anyway to modify it for getElementsByID instead of name? I really need this to finish my website. If any one has any clues or suggestions that would be great.

    [Reply]

    Jon reply on February 16th, 2009 8:49 am:

    function getElementsByName_iefix(tag, name) {

    var elem = document.getElementsByTagName(tag);
    var arr = new Array();
    for(i = 0,iarr = 0; i < elem.length; i++) {
    att = elem[i].getAttribute(“name”);
    if(att == name) {
    arr[iarr] = elem[i];
    iarr++;
    }
    }
    return arr;
    }

    Justin reply on February 16th, 2009 11:26 am:

    Hi Jon,

    Could you give a couple more details about how this new code works? Do we only need to replace the areas that read “name” or are there other changes?

    Walks reply on April 2nd, 2009 7:22 am:

    Hi, just following up on Justin’s question – wondering where exactly this new code needs to be integrated within the previous? Also if it does work, why it hasn’t been added to the code on this page already? Seems to function fine in Firefox and Safari just IE causing the dramas…. as per usual. Thanks for your time and efforts.

    Walks reply on April 2nd, 2009 7:42 pm:

    Found this code that works fine across FF3, Safari3, and IE7.

    function hide_elements(elementids){
    var elems=new Array();
    elems=elementids.split(‘,’);
    var len = elems.length;
    for(i=0;i<len;i++){
    element = document.getElementById(elems[i]);
    element.style.display = ‘none’;
    };
    };
    function show_elements(elementids){
    var elems=new Array();
    elems=elementids.split(‘,’);
    var len = elems.length;
    for(i=0;i<len;i++){
    element = document.getElementById(elems[i]);
    element.style.display = ‘block’;
    };
    };

    [Reply]

    Justin reply on April 2nd, 2009 8:29 pm:

    Hi,

    Thanks for following up on this, does this work in much the same way, one just needs to replace ‘elems’ with the name of our choice? Or do we need to replace ‘element’ as well?

    Justin reply on April 2nd, 2009 8:49 pm:

    OK, I figured just to put my id tags in the () separated by commas, but I can’t get this to work either.

    Justin reply on April 2nd, 2009 9:04 pm:

    Here’s a solution that worked great for me:

    function showonlyone(thechosenone) {
    var example = document.getElementsByTagName(“div”);
    for(var x=0; x<example.length; x++) {
    name = example[x].getAttribute(“name”);
    if (name == ‘example’) {
    if (example[x].id == thechosenone) {
    example[x].style.display = ‘block’;
    }
    else {
    example[x].style.display = ‘none’;
    }
    }
    }
    }

  16. sanjana says:

    November 24th, 2008 at 3:45 am (#)

    hi, nice demo, just a small modificaion i need as i don’t know javascript but will be thankful if this can be implemented.
    1) Same scenario to hide and show of div, div based on different locations but with same name, means all closes or all expands.
    2)there is a cookie that counts how many times visitor has navigated through( pages).
    3)javascript checks cookie value like 1,2,3.
    4) One condition if cookie value is 1 or 2 hide div, else show.
    5) At first div’s are visible but when cookie records value div’s can be hide based on vlue, there should be flexibility to select value.
    Kindly let me know the code, if it can be pasted with an working example.

    [Reply]

  17. Mr-Nilsen says:

    January 5th, 2009 at 3:47 am (#)

    Hello.
    Thanks for all the hide/show snippets !

    But the one with 3 divs where only 1 shows at the time is broke or something.

    cause when i copy/paste the code and try it on my comp the Div #1 get’s stuck and the links don’w work any more. :\

    Could you please mail me a working source or something ?

    Thanks on advance

    // Nilsen

    [Reply]

  18. Filip says:

    January 22nd, 2009 at 4:14 pm (#)

    THank you. You’re a life saver!

    [Reply]

  19. Jesse says:

    January 30th, 2009 at 7:22 am (#)

    Hey…I finally figured out how to do the toggle show/hide demo up near the top but I have a problem…I need to make a table-like set of data for a jobbank. I have created a table with CSS (NO TABLES YEAY!). But the problem is that the javascript I gleaned from here forces me to create an additional div tag (ex: showTextDiv, showTextDiv1, showTextDiv2, etc)…

    The problem is that this is a job bank which will be changing regularly so keeping track of which row has which div will get really confusing really fast.

    Finally my question – how would I structure the javascript to look at the divs individually so that I can keep the “showTextDiv etc” like it is yet still have multiple instances on screen and functioning correctly? here is the page for reference (please note that there are 3 separate divs making the 3 rows work correctly…one main div and an alternate div to change the row color):
    http://www.acmanet.org/index-test.cfm

    [Reply]

    Jesse reply on January 30th, 2009 7:23 am:

    SORRY! My fault, here’s the right link:

    http://www.acmanet.org/jobbank/index-test.cfm

    [Reply]

  20. mia says:

    February 10th, 2009 at 6:50 am (#)

    Thanks for the excellent toggle scripts using images. I am very new to javascript and was just wondering how you would combine this effect with the show only one effect together?

    Thanks again

    [Reply]

  21. Jana says:

    February 17th, 2009 at 2:08 pm (#)

    Hi,

    The “showonlyone” is exactly what I was looking for, but there is that problem with IE.
    Is there anyway to add a variation for IE?

    using: getElementsByID ?

    Thank you.
    Jana

    [Reply]

    Jana reply on March 3rd, 2009 1:49 pm:

    Hi again,

    I found here the script I needed, – the showonlyone – but My website is having links problems at opera and internet explorer. ((of showonlyone)) Could you please help with a code that includes commands that these browsers can recognize??

    thank you.

    [Reply]

    Knix reply on April 8th, 2009 9:12 pm:

    Hi Jana,

    The function has been updated to work in IE6 and IE7. Thanks to Justin and Ulysses.

    [Reply]

  22. Eric says:

    February 20th, 2009 at 11:50 am (#)

    Thanks so much for this! It really helped alot!

    [Reply]

  23. SEO guy says:

    February 23rd, 2009 at 5:37 pm (#)

    ooohhh man this was a great tutorial! thanks for that, i really didnt feel like messing with divs today!

    [Reply]

  24. Jens says:

    February 27th, 2009 at 12:18 pm (#)

    Hi,
    you have made some great hide div’s thingies :-). I especially like the one with the plus and minus sign. I am using it here: http://www.dtails.com/PublishedService?pageID=9&itemcode=Far!
    Can I ask – how can I make the one with the plus and minus sign start the opposite way of what it does now? Meaning, how can I hide the content on load, instead of it being open? Just like the text-link one, with the “Peek-a Boo” in the div. That one is closed on loading
    Thanks a lot for your great work!
    Jens

    [Reply]

    Knix reply on February 27th, 2009 11:37 pm:

    Hi Jens,

    This should be pretty simple. Just start off with div content hidden instead of being visible and keep everything else the same.

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

    [Reply]

  25. Jens says:

    February 28th, 2009 at 4:15 am (#)

    Thank you so much for your help Knix. Worked perfectly :-)!

    [Reply]

  26. Pieter says:

    March 3rd, 2009 at 8:21 am (#)

    Great stuff!
    Many thanks!

    I’m looking for 3 or more div’s to be opened or closed but only one at the time.
    There are three ways in which such a thing can work.
    1. Hide the headers of the ones that are not opened. (Favorit)
    2. Opening a div will close the one that was open. (Not so nice)
    3. You’ll have to close the div, before you can open another. (Okay)

    (English is not my native language, so I do hope you understand what I mean.)

    Pieter

    [Reply]

  27. Christina says:

    March 9th, 2009 at 7:20 am (#)

    Hi there,

    i was hoping if these toggle snippets are compatible with all browsers? and if so, are there any bugs or errors you have encountered with using any?

    thanks,

    sincerely Christina

    [Reply]

  28. amit says:

    March 11th, 2009 at 2:34 am (#)

    The last one doesnot works in IE 6

    please help me.

    [Reply]

    Knix reply on April 8th, 2009 9:11 pm:

    Hi amit,

    The function has been updated to work in IE6 and IE7. Thanks to Justin and Ulysses.

    [Reply]

  29. rc says:

    March 11th, 2009 at 2:02 pm (#)

    Thank you very much for these scripts, they are working great for me.

    I am using the image toggle to open and close multiple divs on one page. Along with the image, now people want the headings to be clickable as well so users can click the image or the heading to open the div.

    The heading name needs to stay the same (not change to expand or collapse, like the examples), so that’s why I’m not sure how to tackle this one. Also, I’m pretty new to javascript.

    Any help with this problem would be most appreciated.

    Thanks.

    RC

    [Reply]

  30. Christina says:

    March 20th, 2009 at 10:57 pm (#)

    Hi there!

    I have recently adapted and modified the second demo that you listed at the top of this page, (e.g. click here: Peek-a-boo!)

    I was wondering if there is a way of modifying the CSS code so the toggling works from horizontal point instead of toggling vertically downwards?

    It would be much appreciated from someone who has knowledge
    on togglings!

    regards,
    Christina, South Australia

    [Reply]

  31. KKT says:

    March 24th, 2009 at 10:12 am (#)

    Hey, you make this very easy to understand which is great. However, I have one important variable I’m wondering if you can solve.

    I’m working on this site: http://raiseupart.com/Cmag/index.php

    You’ll notice that if you click ISSUES, another list of links pops out. That was easy. But, now I need to be able to click on the years that popped out and have another list pop-out.

    I tried changing ids and using the same code, but it seems to be an either/or situation, I guess because that’s what ‘toggle’ implies?

    Thank you!

    [Reply]

  32. Rachel says:

    March 25th, 2009 at 6:46 am (#)

    Hi,

    Thank you for posting so many scripts! My problem is this: I want the links to show on page load, but I don’t want the text to show until after I have clicked the link or button to show the text. Can you create (or point out the script if it is already on this page) a script that does this?

    Thank you!

    [Reply]

  33. Tammie says:

    March 26th, 2009 at 7:44 am (#)

    Love the scripts, they were very helpful.

    the toggle3 function calls on your toggle2 function but you don’t have a function named “toggle2″, both of the first functions are just called toggle. I renamed the function needed to “toggle2″ and it now works. Thought you might like to know this.

    [Reply]

    Knix reply on April 8th, 2009 9:06 pm:

    Thanks for the heads up Tammie.

    I have added the toggle2 JavaScript function code.

    [Reply]

  34. Luke says:

    March 29th, 2009 at 7:52 am (#)

    Hello,

    The last demo (to display only one DIV at a time) is exactly what I’m looking for, but it’s not working on Internet Explorer (version 7 at least).

    I saw some comments about a fix, but it doesn’t seem to be working either.

    Do you have a solution to have this demo work on IE?

    Thanks a lot,
    Luke

    [Reply]

    Knix reply on April 8th, 2009 9:10 pm:

    Hi Luke,

    The function has been edited to work in IE6 and IE7. Thanks to Justin and Ulysses.

    [Reply]

    Luke reply on April 11th, 2009 2:15 am:

    Thanks a lot guys! I’ve just tried it and it works perfectly fine under IE7!

    Great function!

    [Reply]

  35. Ulysses says:

    April 7th, 2009 at 6:54 pm (#)

    To make the SHOWONLYONE code work in both FireFox & Internet Explorer, I have replaced the content of the showonlyone.js file with the following. Works really well.

    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’;
    }
    }
    }
    }

    [Reply]

    Knix reply on April 8th, 2009 9:08 pm:

    Thanks Ulysses! I have replaced the old function with the one you have provided.

    [Reply]

    Pieter reply on May 20th, 2009 10:07 am:

    For you information:
    ShowOnlyOne works with IE5.01, IE 5.5, IE 6, Opera and Safari.
    Great!

    (But ‘name’ is not allowed as attribute for a ‘div’.)

    [Reply]

  36. Anonymous says:

    April 8th, 2009 at 9:16 pm (#)

    Hi Knix,

    The credit should go to: Justin

    Justin reply on April 2nd, 2009 9:04 pm:

    It is that entry that helped me resolve the IE issue.

    Thanks anyway.

    Ulysses

    [Reply]

  37. Joy says:

    April 19th, 2009 at 2:40 pm (#)

    This code is exactly what I’ve been looking for. As much as I want to use it, I’m having trouble getting it to work for me. I am clueless about javascript. I’m really good at copying and pasting!

    The code I have appears to work, but the image for my toggle button appears between the text instead of beside the text. How can I rectify this? The other thing I cannot figure out is how to add more links. I think you call them links. I have a bunch of FAQ for my website and wanted to list each question with the toggle function which opens up to the answer. I really need someone to paste the whole code for me. Your help would be totally appreciated.

    This is the code I have:

    <!–
    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 = ”;
    }
    else {
    ele.style.display = “block”;
    imageEle.innerHTML = ”;
    }
    }

    Let’s use images!

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

    [Reply]

    Ulysses reply on April 19th, 2009 4:11 pm:

    Hi Joy,

    If your code is working but the image is being displayed in the wrong location, you should check the image id and ensure that it is placed inthe correct position.

    Please post your URL, so I can look at the source of the page and work out why it is failing to display in the expected position.

    Ulysses

    [Reply]

    Joy reply on April 19th, 2009 7:11 pm:

    Hi Ulysses

    Thanks so much for responding. Here’s the url to the code I tried on my page:

    http://dejavuapparel.synthasite.com/test4

    As you can see the image is stuck between the two text lines.

    Can you please also tell me how I can add more of those links?

    As I said before.. I’m really really new at this stuff. I’d appreciate a whole code that I can copy.

    Once again, thanks so much for your help.

    [Reply]

    Joy reply on April 19th, 2009 4:42 pm:

    Sorry… it didn’t get the whole code in there. Lemme try again.

    <!– 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 = ”; } else { ele.style.display = “block”; imageEle.innerHTML = ”; } }–> <!– Let’s use images! This demo uses plus and minus images for hiding and showing your div dynamically via JavaScript.–>

    [Reply]

    Joy reply on April 19th, 2009 4:45 pm:

    I can’t figure out how to put the whole code in!!!

    <!– 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 = ‘<!–’; } else { ele.style.display = “block”; imageEle.innerHTML = ‘<!–’; } }–>

    <!– Let’s use images! <!– This demo uses plus and minus images for hiding and showing your div dynamically via JavaScript.–>

    [Reply]

    Ulysses reply on April 19th, 2009 6:29 pm:

    Hi Joy,

    Copy your web site URL on which this code is implemented. Then paste it into this message section.

    Ulysses

    Ulysses reply on April 19th, 2009 10:53 pm:

    Hi Joy,

    Have a look at this page I have setup for you.

    http://dejavu.ulysses.co.nz/

    It is a working example. Contact me via my website to get more details on what you need to do, etc.

    Ulysses

  38. How to hide, show, or toggle your div « Rhyker.com & EUnite.US says:

    May 10th, 2009 at 3:35 pm (#)

    [...] 2008 by rhyker Are you trying to find a way to hide and show your content? Then have a look at this page. It  shows a simple yet elegant way of toggling your content and toggling the control text via [...]

  39. Anthony says:

    May 20th, 2009 at 4:43 am (#)

    Hello,

    I am having some trouble, while this is very good code and suits my purpose, Im not proficient in JavaScript so I am getting slightly stuff.

    What I am trying to do is…

    I have three links as follows: -

    XP VISTA MAC

    When a user clicks XP a section display the relevant info on XP appears, then when a user clicks VISTA, XP closes and VISTA appears.

    However when I click XP, VISTA or MAC in any order, the previous option does not close but the one just clicked open’s.

    Is there anyway you can help me or point to what I need to edit and such?

    If you could provide me with the coding required, that would be extremely helpfull.

    [Reply]

    Pieter reply on May 21st, 2009 1:04 am:

    If you are using “ShowOnlyOne” and didn’t make mistakes in copying en editing it. Things should work.

    [Reply]

    Anthony reply on May 21st, 2009 9:38 am:

    I havent made any mistakes and have only changed what is needed so the relevant info is displayed…

    [Reply]

    Pieter reply on May 22nd, 2009 12:41 am:

    Then there must be a conflict with another javascript or another stylerule.

  40. Pieter says:

    May 21st, 2009 at 1:07 am (#)

    Is there a way to modify “ShowOnlyOne” so it will validate correct? (name attribute is not allowed with DIVs)

    [Reply]

    Pieter reply on May 28th, 2009 5:55 am:

    By the way:
    I used ShowOnlyOne for a vertical menu (in Dutch).
    You can see it at
    http://www.debinnenvaart.nl/binnenvaarttaal/index.php

    Pieter

    [Reply]

  41. Sub says:

    June 1st, 2009 at 2:36 pm (#)

    don’t want to make the comments list much longer so here a short THANK YOU!

    [Reply]

  42. Ulysses says:

    July 2nd, 2009 at 5:49 pm (#)

    Hi Anthony,

    Look at my comment on thread 35 above for the answer to your problem.

    The showonlyone() function needs a different set of code to make it work properly on Firefox & Internet Explorer.

    Hope this helps.

    Ulysses

    [Reply]

  43. Aaron says:

    July 14th, 2009 at 2:04 pm (#)

    Knix,

    I can’t thank you enough for this series of demos. For SEO and cross-browser-compatibility reasons, I don’t like iframes, and the alternative is terrible in IE, so I’ve been looking for a clean way to display one div at a time depending on which link the user clicks. A lot of other demos I looked at had mountains of cumbersome code with questionable results. Your demo not only gives me exactly what I need, it does it will clean, simple code, and keeps all of the content SEO-friendly

    All the Best,
    Aaron

    [Reply]

  44. Kassad says:

    July 16th, 2009 at 2:14 am (#)

    I have created a tab system in wordpress using the showonlyone function. It worked perfectly except that I was not able to make the current tab highlighted.

    Perhaps, you would be so kind to extend a bit your code to achieve this goal.

    I would prefer this solution than the other tabbing systems.
    Much less overhead.

    Very nice work you have done, many thanks for it.

    [Reply]

    Knix reply on July 17th, 2009 12:26 am:

    Hi Kassad,

    Unfortunately, the demo that I have here does not really contain any tabs. Perhaps you can paste your html and I can see what I can do.

    Knix

    [Reply]

    Kassad reply on July 17th, 2009 4:32 am:

    Hi Knix,

    Well, that is what I have so far…

    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';
    }
    }
    }
    }

    a:link, a:active, a:visited {color:#67a063; text-decoration:none; outline:none;}
    a:hover{color:#ca7700;}

    .tab {
    width: 50px;
    border: 1px solid silver;
    background-color: #dde;
    padding: 5px;
    float: left;
    text-align: center;
    }

    .newboxes {
    position: absolute;
    top: 39px;
    left: 8px;
    width: 174px;
    height: 300px;
    border: 1px solid silver;
    background-color: #fff;
    padding: 5px;
    display: none;
    }

    Credits

    Wordpress Content #1

    Archive

    Wordpress Content #2

    Meta

    Wordpress Content #3

    I am sure that you can find a solution to highlight the selected/active tab.

    Thank you very much in advance for your help.

    Kassad

    [Reply]

    Knix reply on July 17th, 2009 8:57 am:

    Hi Kassad,

    You can change the class of the chosen tab via JavaScript and have some styling for the chose tab class:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
    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’;
                newboxes[x].setAttribute("class", "chosentab");
             }
             else {
                newboxes[x].style.display = ‘none’;
                newboxes[x].setAttribute("class", "nonchosentab");
             }
          }
       }
    }

    You will then need to define the chosentab and nonchosentab classes via css. Here is a sample:

    .chosentab {
       border: 1px solid green;
       background-color: #CCC;
    }
    .nonchosentab {
       border: 1px solid #000;
       background-color: #FFF;
    }

    Please note that this code is not tested but I think you will get the gist of it.

    Knix

  45. Hakan says:

    July 17th, 2009 at 7:49 am (#)

    Hi,

    thanks a million for your fantastic job, you made my day.

    cheers

    [Reply]

  46. Kassad says:

    July 17th, 2009 at 1:48 pm (#)

    Something like that…, except that it deals with the content area not with the tabs.

    [Reply]

  47. Danale says:

    July 20th, 2009 at 6:02 pm (#)

    Thanks immensely for the tutorial. I’ve used this on http://mancinostaylor.com, and they’re very happy with it!

    Right now I’m trying to use the “showonlyone”/”newboxes” script to display an art gallery on my site:

    http://danale.com/art

    Ideally, I’d like all the links (“Commission”, “Digital”, etc.) to be stacked one on top of the other, hiding the thumbnails until someone clicks on them. When someone clicks on, say, “Digital”, I’d like the thumbnails for the art to reveal under the word “Digital”, with all the other word links still stacked on top of one another.

    Right now when you refresh the page, each link allows space for the thumbnails to show. It isn’t until you click on one that they all stack on top of each other again, until you click on the new category to allow the art to show.

    It’s most likely something with my CSS, but any help you guys can offer would be greatly appreciated!

    Regardless, thanks a ton for this tutorial! :D

    [Reply]

    Danale reply on July 20th, 2009 6:34 pm:

    Nevermind, I fixed it! :D I needed the first box to have “display:block;” directly in the div, and all the rest to have “display: none;”. After that I can go as nuts with the styling as I want!

    Thank you so much guys!

    Do you think you could make a tutorial on how to make smooth, Flash-like javascript show/hide animations? I’ve seen it done before, just wondering if a small tweak would make it possible.

    [Reply]

    Knix reply on July 20th, 2009 8:39 pm:

    Hi Danale,

    If you could give me a link to an example to what you are referring to, I would be more than happy to do it.

    Knix

    [Reply]

    Danale reply on July 21st, 2009 2:52 pm:

    Actually, I found another source/sample here:

    http://www.dynamicdrive.com/dynamicindex17/animatedcollapse.htm

    Examples 4, 5 and 6 (basically what’s on the right) is what I’m looking to use for my gallery at http://danale.com/art .

    :-)

  48. JD says:

    July 21st, 2009 at 2:03 pm (#)

    Hi,

    I’m looking for something similar to the 3 collapsible boxes. I would like the boxes to close as you click on the next and have the ability for them to be closed completely. I’m making a vertical nav flyout to the left bar.

    Thank you.

    [Reply]

    Knix reply on July 21st, 2009 2:18 pm:

    Hi JD,

    Are you looking for something similar to what you see here:

    http://www.plasterdog.com/layouts/fly_out.html

    Basically, your submenus would appear as you hover over each menu item. If not, please give me a page that shoes a good example.

    Knix

    [Reply]

  49. JD says:

    July 21st, 2009 at 2:45 pm (#)

    Something similar to http://www.sears.com

    I have my page that will always show. I would like to have vertical tab bar that when the tabs are clicked will expand the hiden content.

    What I am trying to do is show or hide a div when a user clicks the link, having multiple divs that belong in the same place so when the user clicks a link it needs to hide the current div, and then show the new one. I am a newbie to Javascript.

    [Reply]

  50. Ryan says:

    July 28th, 2009 at 4:26 am (#)

    Please help,I’m trying to use the demo which uses the functions toggle 2 and toggle 3 but its not working for me, there must be something I missed. I’m a newbie.
    It is showing on the webpage but its already collapse…nothing happens when I click it. Is there some stuff that I need to do before I get it to work? I copied the javascript in the head portion of my html and the table in the body. Please help, I’ve been cracking this case for 3hrs now and nothing works. Thanks in advance

    [Reply]

  51. jQuery Modal says:

    August 1st, 2009 at 4:30 am (#)

    [...] a twitter one, that can be achived a whole load of different ways. How to hide, show, or toggle your div __________________ Domain Diagnosis [...]

  52. Tim says:

    August 12th, 2009 at 4:25 pm (#)

    I used your very first example, but created 3 different DIV sections each controled by a different button. How can I make the visible DIV hide when a second is clicked instead of having to toggle off first?

    function toggle1() {
    var ele = document.getElementById(“toggleText1″);
    var text = document.getElementById(“displayText1″);
    if(ele.style.display == “block”) {
    ele.style.display = “none”;
    text.innerHTML = “ ABOUT ”;
    }
    else {
    ele.style.display = “block”;
    text.innerHTML = “ ABOUT ”;
    }
    }

    function toggle2() {
    var ele = document.getElementById(“toggleText2″);
    var text = document.getElementById(“displayText2″);
    if(ele.style.display == “block”) {
    ele.style.display = “none”;
    text.innerHTML = “ FOLIO ”;
    }
    else {
    ele.style.display = “block”;
    text.innerHTML = “ FOLIO ”;
    }
    }

    function toggle3() {
    var ele = document.getElementById(“toggleText3″);
    var text = document.getElementById(“displayText3″);
    if(ele.style.display == “block”) {
    ele.style.display = “none”;
    text.innerHTML = “ CONTACT ”;
    }
    else {
    ele.style.display = “block”;
    text.innerHTML = “ CONTACT ”;
    }
    }

    [Reply]

  53. Erwin says:

    August 14th, 2009 at 7:44 am (#)

    I need to show and hide all the div’s. But in one of the example there one almost what i’m looking for.

    But it working funky. I need when i press the bottom hide all div and when i click again show all.

    The problem is when i click on one of the single div it hide, but after i click hide all the function hide all div’s but the one that was hide it show..

    Can i explain my self. It hard to explain myself sorry

    Pls help :( i’m pulling my hair off

    [Reply]

  54. Brent says:

    August 26th, 2009 at 2:20 pm (#)

    Love the ‘onlyshowone’ script as it does EXACTLY what I want it to do. My problem is with IE and its inability to handle onclick events within list options. Specifically, I have a dropdown menu that I want a user to select from in order to toggle the visibility of a second menu. This works perfectly in Firefox, but not in IE because of the aforementioned lack of support for ‘onclick’ within the options.

    A sample page is here: http://rossow.us/tmp/sample.html

    The links across the top of this sample page demonstrate what I want the corresponding menu options to do (which they do in Firefox, just not IE). I know this problem is entirely unrelated to this set of fine scripts, but if someone could point me toward a solution that works in IE I’d be more than grateful. I’m a javascript novice at best, so thanks for your patience.

    [Reply]

  55. Ulysses says:

    August 26th, 2009 at 6:43 pm (#)

    Hi Brent. Look up the code changes that you require on post number 35 above.

    To make the SHOWONLYONE code work in both FireFox & Internet Explorer, I have replaced the content of the showonlyone.js file with the following. Works really well.

    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’;
    }
    }
    }
    }

    [Reply]

    Brent reply on August 26th, 2009 6:59 pm:

    Thanks, Ulysses, but that isn’t the question. (That’s the code I’m already using.) The problem I’m having is that IE doesn’t recognize ‘onclick’ events within OPTION tags and therefore the script is never called. I’m looking for a workaround.

    You can look at the full source code for the page I linked above, but in a nutshell here’s what I’m using right now to call the ’showonlyone’ script:

    Retailer

    Firefox handles it beautifully — when you select that option from the dropdown menu, only the DIV with id ’scope3′ is displayed. But when you select the same thing in IE, nothing happens. This is well-documented as not working, but I have yet to find directions I can understand on how to work around the issue. (I’ve seen references to putting an ‘onchange’ trigger in the SELECT tag, but I have absolutely no idea how to do that.)

    I know this isn’t directly related to the code presented here, but I hoped someone could help anyway. Thanks again!

    [Reply]

    Brent reply on August 26th, 2009 7:05 pm:

    Sorry — it didn’t show the code. Let’s try again…

    <option value=”Retailer” onclick=”javascript:showonlyone(’scope3′);”>Retailer</option>

    [Reply]

    Brent reply on August 27th, 2009 6:30 am:

    Never mind — figured it (‘onchange’) out on my own after a good night’s rest. Thanks again for a terrific script!

  56. Jadranko says:

    August 27th, 2009 at 2:34 pm (#)

    Hi!
    I have a problem. I’m using first javascript example on this great page. But I’m using it in a table.

    firstfirstfirst
    secondsecondsecond
    thirdthirdthird

    fourth
    fifth

    It looks great in explorer 8, but looks awful in firefox. What am I doing wrong?
    Pleas help.

    [Reply]

  57. John says:

    August 28th, 2009 at 10:26 am (#)

    Hello there,

    I was trying to modify your showonlyone script to do a design that opens up another set of tabs which then opens the last div which will have content. having a bit of trouble with that and its inability to work across separate divs rather than tables. is there a way to do this?

    Thanks!

    Untitled Document

    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’;
    }
    }
    }
    }

    collapse

    collapse

    Div #3

    Div #2

    Div #2

    collapse

    collapse

    [Reply]

  58. Veronica says:

    September 2nd, 2009 at 11:54 am (#)

    I am trying to do this but using a select drop down box is that possible?

    [Reply]

  59. Courtney says:

    September 3rd, 2009 at 12:23 pm (#)

    Great demo!

    Question about Toggle3. How would I change the header STYLES when items are open? For instance I want the Collapse button to turn yellow once I’ve revealed DIV #1,2,3.

    Courtney

    [Reply]

  60. Andale says:

    September 5th, 2009 at 8:50 pm (#)

    I was trying use your code in a strange way. I thought maybe I could use this to hide my site and play a gif or some flash for a few seconds (as a preloader) but I have 1) no idea how to automate it or set a timer in java, also 2) I have no idea what i’m doing with javascript.

    anyone able to point me in a direction?

    [Reply]

  61. Rekha says:

    September 18th, 2009 at 11:48 pm (#)

    Hi,

    I am working on ERP product.I have used images plus and minus for displaying div.
    its working fine.
    but i have many buttons like clear,new, refresh etc on my page.
    when i click these buttons,the hiding div is visible again.
    i want the div to be hided until the user clicks on the plus buttton.

    [Reply]

  62. David says:

    October 1st, 2009 at 4:23 am (#)

    Hi

    I need all the divs to be collapsed when the user lands on the page, then when they click on the link the content appears, then when they click on another link the previous content is hidden and the new links content is shown.

    Not sure I go about achieving this?

    Thanks

    [Reply]

  63. arpit says:

    October 4th, 2009 at 10:12 am (#)

    I want to Hide the div initially when the page was loaded.
    So what change in js should be done?
    please help.
    thanx in advance.

    [Reply]

    Knix reply on October 4th, 2009 10:27 am:

    Hi arpit,

    Hiding the div initially will not require a change in the JavaScript. Instead, just add styling to the div itself. I will show an example with inline CSS but it is best to place it in your stylesheet:

    <div id="mydiv" style="display: none;">My content</div>

    I hope this helps.

    [Reply]

  64. -clayton- says:

    October 6th, 2009 at 11:00 pm (#)

    http://www.ifaq.gov.sg/toteboard/apps/fcd_faqmain.aspx

    above is a link of the demo i would like to request your help for,
    where a seperate button is used to show and hide the toggled DIVisions..
    please help.

    [Reply]

  65. Joseph says:

    October 9th, 2009 at 9:59 am (#)

    I’m using the first block of code “Peek a boo”

    Could you give me an example of having multiple hide show links on a single page?

    [Reply]

  66. Gary says:

    October 20th, 2009 at 8:53 am (#)

    Hi Knix,

    This code is great, clean, simple, just what I needed. I don’t know what I would do if not for the hard work of code-gurus like you.

    Here’s my implementation: http://www.range37.com/training.html

    [Reply]

  67. Prasanth says:

    November 3rd, 2009 at 9:12 pm (#)

    Thanks!!!!!!!!!!

    Very Interesting & Usefull for noobs!!!!!!!!!!!!!

    Thanks you once again!!!!!!!!!!!!!!!!!!!

    This is the one I had searched!!!!!!!!!!!!!!!!!!

    [Reply]

  68. Jebamani says:

    November 4th, 2009 at 6:12 am (#)

    This article is really helpful

    [Reply]

  69. Sharon says:

    November 9th, 2009 at 10:16 am (#)

    I can get the first answer, open to the first question, but how does one seperate the following answers so they don’t pop up under the first question, as an answer? I cannot get the other answers to open under the correct question, when showing decending questions and answers. Anybody know what I’m doing wrong? I have tried lots of formulas, but just can’t get it to work. Is there anyone out there that can change the following code to make this work? Thank you.
    1×1=

    function toggle() {
    var ele = document.getElementById(“toggleText”);
    var text = document.getElementById(“displayText”);
    if(ele.style.display == “block”) {
    ele.style.display = “none”;
    text.innerHTML = “show answer”;
    }
    else {
    ele.style.display = “block”;
    text.innerHTML = “hide”;
    }
    }

    show answer
    1

    1×2=

    function toggle() {
    var ele = document.getElementById(“toggleText”);
    var text = document.getElementById(“displayText”);
    if(ele.style.display == “block”) {
    ele.style.display = “none”;
    text.innerHTML = “show answer”;
    }
    else {
    ele.style.display = “block”;
    text.innerHTML = “hide”;
    }
    }

    show answer
    2

    1×3=

    function toggle() {
    var ele = document.getElementById(“toggleText”);
    var text = document.getElementById(“displayText”);
    if(ele.style.display == “block”) {
    ele.style.display = “none”;
    text.innerHTML = “show answer”;
    }
    else {
    ele.style.display = “block”;
    text.innerHTML = “hide”;
    }
    }

    show answer
    3

    [Reply]

  70. 7 Ways to Use CSS to Rank Better | Unstuck Digital says:

    November 11th, 2009 at 6:24 pm (#)

    [...] a great example of this at RandomSnippets.com (complete with the code that drives the [...]

  71. araç sorgulama says:

    November 29th, 2009 at 3:50 pm (#)

    Hi all,

    Reloading the whole page calls the content back by default. What if I don´t need the content status (none or block) to be changed by reloading the page? Would be possible?

    [Reply]

  72. Pandora says:

    December 7th, 2009 at 9:56 pm (#)

    Thank you for this great post. I have been looking for a good working version in jquery, yui, moo-tools etc and this one seems to work best.. ;)

    [Reply]

  73. Brian says:

    December 17th, 2009 at 2:56 pm (#)

    I have used this and thought everything was working great… Until someone pointed out that in IE7 (probably other flavors of IE as well) our page gets messed up once you use the toggle. We have a header and footer, and the footer doesn’t float down when you click on the show and the extra text is pushed down. In fact.. it looks like the footer moves up!

    Then when you click hide, the text slides up.. but there is still part of the web page hidden by the now moved up footer.

    Is there any way to resolve this quickly?

    [Reply]

    Brian reply on December 17th, 2009 2:59 pm:

    I should have stated I was using the first demo of the peek-a-boo.

    [Reply]

  74. FF says:

    December 17th, 2009 at 3:20 pm (#)

    Hi,

    thanks for the trick! How about if you want to pass the toggle info through a page refresh? When you press show and refresh the page, the setting is reset and goes back to hide. So, how does this work through a page refresh?

    [Reply]

  75. [MW2CC] Admin says:

    December 22nd, 2009 at 1:15 pm (#)

    This was an awesome guide!!!

    I changed the code a little bit so that it closed a certain division completely. It works great! Check it out:
    http://www.modernwarfare2cc.com

    The only problem is that since I defined it in a general template, when I open up a different page, it comes up again. Is there any way to make the website (or computer) remember that the user has closed the div? That way, when a user closes it on one page and goes to a different page, it won’t show up again.

    Thanks!

    [Reply]

  76. Chuck McQuilkin says:

    January 12th, 2010 at 12:12 am (#)

    Great demo thanks. Do you know if there’s there any way to re-write the last demo in jquery?

    [Reply]

  77. Ken says:

    January 12th, 2010 at 12:58 pm (#)

    Just what I was looking for, works great. Thanks. My pure CSS version worked fine for all browsers except for IE, it didn’t repaint the rounded left and right corners correctly upon expansion.

    [Reply]

  78. Toe-Knee says:

    January 13th, 2010 at 3:00 pm (#)

    Does anyone know how to make it so that i can use an image and text in the link?

    i.e. this does not work, when i click the text, the link dissapears…

    Click Link

    i am using Toggle5 with images… but wanted to add text as well.

    thx

    [Reply]

  79. Hanan Ali says:

    January 14th, 2010 at 7:33 am (#)

    Thanks Alot, it saved my time :)

    [Reply]

  80. bornholy says:

    January 17th, 2010 at 7:25 pm (#)

    Hi, May i know how to show text and image in –>> .innerHTML ??

    Can that be text.imageEle.innerHTML ???

    [Reply]

  81. Rosie says:

    January 23rd, 2010 at 9:49 pm (#)

    Very useful, thank you!

    [Reply]

  82. bornholy says:

    January 24th, 2010 at 8:25 pm (#)

    Hi, i still didnt get my answer, its ok… i have one more questions !

    I’m using Toggle5 with images too, how do i duplicate the effect to another table using the same java/html code on the same page ?

    cus, it only works on one layer .. does it have a given name ?

    [Reply]

  83. phi says:

    January 28th, 2010 at 1:37 pm (#)

    thanks a lot for the code! certainly the most thorough example of showing/hiding divs i’ve found on the internet.

    [Reply]

  84. Russell Day says:

    January 31st, 2010 at 1:55 am (#)

    Hi,
    I have a problem which seems like it should be routine but I cannot find an answer to it.

    I have a log file which has two levels of detail: results and analysis. I want the page to display only the results by default, with a link that shows the analysis on demand.

    There are an unknown number of each type of entry. I have created an “analysis” id and a “results” id and I assign them appropriately, so the report has many “analysis” divs and many “results” divs.

    What I want is that when I click the “Show” link, all the analysis divs become visible. Every example I have found on the internet only reveals the first div with id “analysis”. The rest of them stay hidden.
    There must be a solution, but I cannot find it.

    [Reply]

  85. Olax says:

    February 27th, 2010 at 2:31 am (#)

    Thank you so very much for the ’showonlyone’part above! I’ve been looking for hours for that!

    [Reply]

  86. Mr Butterfly says:

    March 4th, 2010 at 4:27 am (#)

    Hi there,
    Firstly, thanks a MILLION for the demo and corresponding code. Works like a treat and I’m eternally grateful.

    Just to push things a little further, I am wanting to have a ’slide’ effect with the show/hide action and was hoping you could advise how I need to adjust my code:

    function toggle(showHideDiv, switchImgTag) {
    var ele = document.getElementById(showHideDiv);
    var imageEle = document.getElementById(switchImgTag);
    if(ele.style.display == “block”) {
    ele.style.display = “none”;
    imageEle.innerHTML = ”;
    }
    else {
    ele.style.display = “block”;
    imageEle.innerHTML = ”;
    }

    Hope to hear from you soon!
    Thanks and regards.

    [Reply]

  87. Steve says:

    March 6th, 2010 at 12:11 am (#)

    Hi Knix,

    Firstly I love this script… Great for massive amounts of content in tiny little spaces and very SEO savy.

    I have run across another use for this script that you may want to use, but it requires a little modification that’s out of my league (JS Newb). What I wanted the script to do is toggle trough divs via a single next button or link.

    My client wants a few fact files shown one at a time and the ability to see the next fact by clicking a link. I tried some random quote generators but with only 4 facts atm they tend to show the same fact over and over and need the page to be reloaded to change.

    Do you think it is possible to add this to your demos?

    Regards,
    Steve

    [Reply]

  88. Mahabub says:

    March 21st, 2010 at 11:00 pm (#)

    function showstuff(boxid) {
    document.getElementById(boxid).style.visibility = “visible”;
    document.getElementById(boxid).style.display = “block”;
    }

    function hidestuff(boxid) {
    document.getElementById(boxid).style.visibility = “hidden”;
    document.getElementById(boxid).style.display = “none”;
    }

    Show again

    BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH BLAH

    hide again
    plz try this .

    [Reply]

  89. paul_cmfx says:

    March 22nd, 2010 at 11:57 am (#)

    Hi. I used the showonlyone code on each of the following pages and it works terrific:

    Weddings
    Commercial
    Training
    Seminars/Workshops
    Performances/Recitals
    Occasions/Parties
    Music
    Documentary

    However, it creates a new problem in IE 7. Each of those links should open in my IFRAME called “sizeframe”.

    After I have visited my first page, eg. weddings, and the showonlyone function has been called/clicked at least once, the links I have in the first snippet do not open up in my IFRAME any longer. Instead they open in a New Window. Any ideas why this is happening? I know it is caused somehow by the showonlyone javascript, because without it, my links open just fine.

    [Reply]

  90. Heidi says:

    March 29th, 2010 at 9:46 am (#)

    I love this script, but I need to be able to click on the link again to completely collapse the divs (and have NOTHING expanded). Right now, clicking on the same link after expanding the div makes the div remain expanded.

    So, I guess I want to combine this and a ‘toggle’ script, but I don’t even know where to begin.

    Is there any way somebody could help me with the code for that?

    [Reply]

    Heidi reply on March 29th, 2010 9:48 am:

    Whoops, forgot to specify which code I was using! I’m using the “new” demo, with only one div displayed at a time. (showonlyone)

    [Reply]

  91. Anonymous says:

    May 2nd, 2010 at 11:21 pm (#)

    Thank you for the onlyshowone multiple div script. I was able to use the same script to change the style of the links so that they change when the div changes. This was for thumbnail images that open a larger gallery image, so the thumbnail image has a border of one color when selected and another when unselected.


    function change(link) {
    var th = document.getElementsByTagName("img");
    for(var i=0; i<th.length; i++) {
    name = th[i].getAttribute("name");
    if (name == 'th') {
    if (th[i].id == link) {
    th[i].className = 'sel';
    }
    else {
    th[i].className = 'unsel';
    }
    }
    }
    }

    [Reply]

  92. Aron says:

    June 1st, 2010 at 7:51 am (#)

    I’m looking Toggle 3, is it possible to have it so when the site loads it starts collapsed?

    [Reply]

    Knix reply on June 1st, 2010 2:44 pm:

    Hi Aron,

    To start with the divs collapsed, simply edit your CSS so that the divs are hidden:

    #mydivId {
    display: none;
    }

    That should do it!

    [Reply]

    Aron reply on June 2nd, 2010 3:39 am:

    thanks for the quick reply, i’ll try that now

    [Reply]

  93. bobin says:

    June 15th, 2010 at 3:19 am (#)

    Hi i am working with toggle5, is it possible to work link the text along with the + , – images?

    I am using 13 instances, Thirteen has different texts

    Please any help will the highly appreciated

    [Reply]

  94. Matt says:

    June 15th, 2010 at 6:24 am (#)

    Thanks for compiling and usefully displaying all this info. Great learning resource :]

    [Reply]

  95. Mithila says:

    June 16th, 2010 at 1:52 am (#)

    Hello
    I am having a toggling div tag. I want div tag to overlap contents below it. whenever it is visible it changes that row height to height of div tag.

    [Reply]

  96. Asmi says:

    June 30th, 2010 at 11:41 pm (#)

    Hi i am working with toggle5 where plus and minus images are used for hiding and showing div. I hv created 3 such boxes.. n gave it diff ids. when u click minus button for the very first time it doesn’t work however every click aft tht works fine.

    [Reply]

    Knix reply on June 30th, 2010 11:49 pm:

    Hi Asmi,

    Make sure the css for your divs are set to:

    #yourDivIds {display: block;}

    Allen

    [Reply]

  97. Asmi says:

    July 1st, 2010 at 12:00 am (#)

    Hey thanks a lot.. tht solved my problem..

    [Reply]

    Knix reply on July 1st, 2010 12:02 am:

    No problem =)

    Allen

    [Reply]

  98. Eiolon says:

    July 13th, 2010 at 7:36 pm (#)

    I am using this script to toggle when a form is being shown. However, when the form is submitted, if there is an error, the DIV disappears when the page reloads. Any way to keep the DIV shown after the page is reloaded?

    [Reply]

Comments or feedback...

If you have any demos that you would like to request, please do so.

Click to cancel reply

Recent Posts

  • Sorting 2D associative arrays in PHP
  • Dynamic or on-the-fly percentage calculations with JavaScript
  • The dangers of embedding the notorious “void(0)” JavaScript code in the href attribute of the “a” tag
  • How to randomly order or select rows in a MySQL query
  • How to convert MySQL timestamp to PHP date type

Recent Comments

  • Anders K on Simulate a button click via JavaScript
  • john on How to find and replace text dynamically via JavaScript
  • Eiolon on How to hide, show, or toggle your div
  • Use label as distant button in HTML – Community – travellin' meets real life on Simulate a button click via JavaScript
  • gaurav on Simulate a button click via JavaScript

Archives

Categories

  • javascript
  • mysql
  • php

©2010 Random Snippets