Javascript show/hide feature help

Hi, I am having some problems getting some javascript to work properly for a navigation system on my website... at present I have....
<div id="content1"></div>
<div id="content2"></div>
<div id="content3"></div>

Open in new window

Div "content1" is displayed when the page is loaded, the others are hidden. I have done this using 'display:block' and 'display:none' css rules.

#content1 {
	display: block;
#content2 {
	display: none;
#content3 {
	display: none;

Open in new window

I then have the following links:

<a href="javascript:void(0)" onclick="showhide('content1');" >Content 1</a>
<a href="javascript:void(0)" onclick="showhide('content2');" >Content 2</a>
<a href="javascript:void(0)" onclick="showhide('content3');" >Content 3</a>

Open in new window

with the following javascript:

var divState = {}; 
function showhide(id) {
    if (document.getElementById) {
        var divid = document.getElementById(id);

        divState[id] = (divState[id]) ? false : true; 
        for (var div in divState){
            if (divState[div] && div != id){ 
                document.getElementById(div).style.display = 'none'; 
                divState[div] = false; 
        } = ( == 'block' ? 'none' : 'block');

Open in new window

The idea is that, when the link relating to each div is clicked on only that div is displayed, the others get hidden. The problem with this current script is that on first use, the div that is displayed on page load does not dissapear. Also, when a link is clicked on twice the div dissapears altogether.

Basically, is there anyway to adjust this javascript so that it first hides the div that is already displayed, but also not hide a div if the user clicks the same link twice.

I am inclined to think the best bet would be to use another script that uses classnames, but having tried cannot find one to work.

Any help would be appreciated.

- Rob
Who is Participating?
smeghammerConnect With a Mentor Commented:

Try this:

<p>some static text...
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /></p>
  <!-- insert links dynamically here -->
  <div id="links"></div>
  <!-- the blocks to toggle: -->
  <div id="x1">  <p>Lorem ipsum dolor sit amet consectetuer et nisl Nunc Donec Cras. Hac urna elit mauris Donec cursus augue Nullam in arcu In. A id auctor lacus eros suscipit tincidunt sagittis Aenean diam ultrices. Adipiscing eget vitae neque id aliquam congue massa et montes non. Consequat dui Nullam tempus elit eget.</p></div>
  <div id="x2"><p>In natoque tempor Aliquam tempor malesuada wisi leo Aenean feugiat leo. Et laoreet porta turpis lorem est fames pretium ligula mauris a. Sociis urna id ipsum vitae nulla ut et Pellentesque neque dictumst. Risus Curabitur Nunc semper at Quisque Vivamus mus habitasse leo pede. Magna mi eros Nullam malesuada pede.</p></div>
  <div id="x3"><p>In cursus hendrerit Curabitur magna convallis Curabitur habitant justo Curabitur pellentesque. Vivamus congue nunc at libero non hendrerit ac velit Nam euismod. Nibh Quisque enim dolor wisi pede id feugiat condimentum lobortis tempus. Vivamus sit justo Nullam wisi orci Fusce ipsum Ut id ac. Metus pellentesque est libero ut sem purus.</p></div>

<script type="text/javascript">

//get relevant DIVs:
function initialiseDivs(x)
   var container = document.getElementById("links");
    var anchors;
    var anc
    var ancText
    var currElem;
    for(var a=0;a<x.length;a++)
      anc = document.createElement("a");
      ancText = document.createTextNode("[" + x[a] + "]"); 

      //attach handler to anchor:
      anc.onclick = function()
        //get the elem to show:
        currElem = document.getElementById("_")[1]);
        for(var a=0;a<x.length;a++)
          var elem = document.getElementById(x[a]);
          //set all hidden:

        //and set selected to visible:"block";
        return false;
      //attach the new anchor element:
      var elem = document.getElementById(x[a]); //the anchor tag
      //set initial display state:
      if(a==0)  //the first one, but you can add logic here to decide which DIV is initially visible.

//The only dynamic bit. Specify your DIV IDs to find here:
var divsToFind = new Array("x1","x2","x3"); 

Open in new window

Basically, I assumed the basic page structure as above, and that you have the ability to amend the code yourself...

DIV IDs are arbitrary (x1 - x3 here)
You can insert a DIV into which the clickable anchors will go (id="links" here)

The code uses an array of the DIV IDs on the current page you are looking for, and passes this on to the function to build the initial state (one visible, others hidden) and build the associated anchor tags. The anchor tags have an anonymous function attached to handle the click event. This function simply swaps the toggle state of the specified DIVs.

Note I added a bunch of BR tags to demonstrate the page not jumping back to the top (note the return false; on the anonymous function)

Additional logic can be built in if required.
rob22888Author Commented:
Hi, thanks for your response.

It works, however, it is not quite what I am looking for. I realise and apologise for the fact I did not mention this in the original post, but there are mulitple sections on the webpage where content will need to be 'toggled'. Therefore, I need a script that is adaptable, hence why i currently have a script which uses the 'onclick' bit in the link.

I needs to work a bit like this, unless you far more qualified JS programmers have a better solution.... I have written it in pseudocode:

Gather class name of all relevant divs & id of div to be displayed

If (div with certain id is already set to 'display:block')
         do nothing
          set all divs with certain class name to 'display:none'
          display div with certain id to 'block'

Open in new window

Also, when the user clicks the link it must not jump back to the top of the page in any circumstances, that is why my links currently use 'javascript:void(0)' rather than the hashtag.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.