Evan Schmidt
Evan Schmidt

Reputation: 35

Javascript toggle (one at a time)

Im looking for a simple way to only have one div open at a time. Im using an accordian style vertical navigation and when I click on one, it displays the div below, when I click on another, it does the same. I would like the previous div to hide again when I click on a different nav link.

This is the javascript im using to get it to open and close:

<script type="text/javascript">
<!--
function toggle_visibility(id) {
   var e = document.getElementById(id);
   if(e.style.display == 'block')
      e.style.display = 'none';
   else
      e.style.display = 'block';
}
//-->
</script>

Is there something else I can add that will close the div if another is opened?

Upvotes: 0

Views: 533

Answers (4)

Felix Kling
Felix Kling

Reputation: 816422

A very simple way would be to just keep track of the previously opened element:

(function() { // using an IIFE to prevent polluting the global namespace
    var opened_element = null;

    window.toggle_visibility = function(id) {
       var e = document.getElementById(id);
       if (opened_element && opened_element !== e) {
           opened_element.style.display = 'none';
       }
       if(e.style.display == 'block') {
          e.style.display = 'none';
       }
       else {
          e.style.display = 'block';
       }
       opened_element = e;
    };
}());

Upvotes: 3

Ford
Ford

Reputation: 2597

Since you're not using JQuery, I assume you want a Javascript answer, you can do this by giving your divs some unique classname like "menudiv", then appending something like the following to your function:

var menu_divs = document.getElementsByClassName("menudiv");
for ( var i = 0; i < menu_divs.length; i++ ) {
    if ( menu_divs[i] != e )
        menu_divs[i].style.display = 'none';
}

Upvotes: 0

Matt
Matt

Reputation: 4117

The best way is to:

  • Use CSS to hide all of your DIVs
  • When you want to display one; add a class to your open div called "active" or whatever
  • Then apply css to that class with display: block or what ever.

As Jason said in his comment you can do this with jQuery or you can do it without.

jQuery will provide animation support and easier manipulation of classes.

jQuery Toggle Class

Upvotes: 0

Jason
Jason

Reputation: 349

Give them all the same class. Hide them all by classname and show the one you clicked on with the id passed.

Upvotes: 0

Related Questions