Solved

Javascript show/hide feature help

Posted on 2013-06-04
5
218 Views
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
0
Comment
Question by:rob22888
5 Comments
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
0
 
LVL 1

Author Comment

by:rob22888
Comment Utility
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
else 
          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.
0
 
LVL 4

Accepted Solution

by:
smeghammer earned 500 total points
Comment Utility
Hi,

Try this:

<html>
<head>
<title>toggle</title>
</head>
<body>
<h1>Intro</h1>
<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>
<div>
  <!-- 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>
</div>

<script type="text/javascript">

//get relevant DIVs:
function initialiseDivs(x)
{
  try
  {
   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");
      anc.href="#";
      anc.setAttribute("id","toggle_"+x[a]);
      ancText = document.createTextNode("[" + x[a] + "]"); 
      anc.appendChild(ancText);

      //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++)
        {
          //toggle
          var elem = document.getElementById(x[a]);
          //set all hidden:
          elem.style.display="none";
        }

        //and set selected to visible:
        currElem.style.display="block";
        return false;
      }
      
      //attach the new anchor element:
      container.appendChild(anc);
      
      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.
      {
        elem.style.display="block";
      }
      else
      {
        elem.style.display="none";
      }
    }
  }
  catch(e)
  {
    alert(e.message);
  }
} 

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

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.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

In this article, we'll look how to sort an Array in JavaScript, including the more advanced techniques of sorting a collection of records either ascending or descending on two or more fields. Basic Sorting of Arrays First, let's look at the …
In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
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…

763 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now