Page 1 of 1

Javascript to hide all other menus when one is shown

Posted: Fri Feb 26, 2010 1:22 pm
by lshaw
I have the following javascript which displays a list when the item at the top of that list is clicked:

Code: Select all

 
function showmenu(menu_id)
        {
            document.getElementById(menu_id).style.display='block';
        }
 
This is the HTML code used to implement the function

Code: Select all

 
 <ul id="top_menu">
                  <li id="top_menu" onclick="showmenu('menu1')">
                  About Us
                  </li>
              <ul id="menu1" class="menu">
                  <li>About the club</li>
                  <li>How to find us</li>
                  <li>Contact Us</li>
              </ul>
                <li id="top_menu" onclick="showmenu('menu2')">
                      Training
                  </li>
                  <ul id="menu2" class="menu">
                      <li>Training</li>
                  </ul>
              </ul>
 
The Question
My question is, how can i hide other menus when one is open, so a user can only open one menu at a time
For example, a user is viewing menu 1 and clicks the menu 2 link, I need to hide menu1

Thanks,

Lewis

Re: Javascript to hide all other menus when one is shown

Posted: Fri Feb 26, 2010 2:25 pm
by AbraCadaver
First, you have multiple tags with the same id, which is invalid. In general, to do what you want you need to do the following (I think):

1. getElementsByTagName('ul')
2. Loop through the elements and check if .className = 'menu' and then set .style.display = 'none'
3. Finally set .style.display = 'block' on the element that was clicked

Re: Javascript to hide all other menus when one is shown

Posted: Fri Feb 26, 2010 2:55 pm
by lshaw
Thanks I have this working now

Re: Javascript to hide all other menus when one is shown

Posted: Fri Feb 26, 2010 3:00 pm
by AbraCadaver
I'm not a javascript guru and I don't do much with menus, but here is a quick test I did. The only way I know of to capture an onclick() is to use a link or a form control:

Code: Select all

function showmenu(menu_id)
{
    menus = document.getElementsByTagName('ul');
 
    for(var i in menus) {
        if(menus[i].className == 'menu') {
            menus[i].style.display = 'none';
        }
    }
    document.getElementById(menu_id).style.display = 'block';
}

Code: Select all

<ul>
    <a href="#" onclick="showmenu('menu1')">
        <li>About Us</li>
    </a>
    <ul id="menu1" class="menu">
        <li>About the club</li>
        <li>How to find us</li>
        <li>Contact Us</li>
    </ul>
    <a href="#" onclick="showmenu('menu2')">
        <li>Training</li>
    </a>
    <ul id="menu2" class="menu">
        <li>Training</li>
    </ul>
</ul>

Re: Javascript to hide all other menus when one is shown

Posted: Fri Feb 26, 2010 3:04 pm
by AbraCadaver
lshaw wrote:Thanks I have this working now
OK, how did you get an onclick() in a li to work?