Javascript show/hide feature help

Posted on 2013-06-04
Medium Priority
Last Modified: 2013-11-29
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; 
        divid.style.display = (divid.style.display == '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
Question by:rob22888
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 82

Expert Comment

ID: 39218724

Author Comment

ID: 39220748
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.

Accepted Solution

smeghammer earned 2000 total points
ID: 39603959

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(this.id.split("_")[1]);
        for(var a=0;a<x.length;a++)
          var elem = document.getElementById(x[a]);
          //set all hidden:

        //and set selected to visible:
        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.

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

764 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question