Search code examples
javascripthtmlmenubar

closing the submenu on clicking the next menu


I have the following javascript :-

 <script language="javascript" type="text/javascript">
  function HideandUNhideObj(ThisObj){
  nav=document.getElementById(ThisObj).style
  if(nav.display=="none"){
  nav.display='block';
  }else{
  nav.display='none';
  }
  }
 </script>

And I have the following HTML code for the menus and sub menus

 <ul>
 <li><a href="#" onclick="HideandUNhideObj('div1');">Menu 1</a>
 <div style="display: none;" id="div1">
   <ul>
     <li><a href="#">Submenu 1</a></li>
     <li><a href="#">Submenu 2</a></li>
     <li><a href="#">Submenu 3</a></li>
     <li><a href="#">Submenu 4</a></li>
   </ul>
  </div>
 </li>
</ul>
<ul>
<li><a href="#" onclick="HideandUNhideObj('div2');">Menu 2</a>
 <div style="display: none;" id="div2">
   <ul>
     <li><a href="#">Submenu 1</a></li>
     <li><a href="#">Submenu 2</a></li>
     <li><a href="#">Submenu 3</a></li>
       <li><a href="#">Submenu 4</a></li>
   </ul>
 </div>
 </li>
</ul>

But on one click makes a submenu appear and clicking it again hides it.

I need to hide the sub menus, when we click on the next menu. Only one Menu should open the sub menus in it.

Now, I can open two menus, having its sub menus in it, and on clicking the menu only, will hide those.

Please help.

The sample menu I created :-

enter image description here


Solution

  • In case you have more than just 2 submenus, the @Ashish's answer is not very scalable.

    I've played a little bit wit your code and got something like this http://jsfiddle.net/LfAbb/ :

    function HideandUNhideObj(submenuId){
        hideAllSubmenus();
        showSubmenu(submenuId);
    }
    
    function hideAllSubmenus() {
        var submenus = document.getElementsByClassName("submenu");   
        for (var i = 0; i < submenus.length; ++i) {
            var submenu = submenus[i];
            hideSubmenu(submenu);            
        }
    }
    
    function hideSubmenu(elem) {
        elem.style.display = "none";
    }
    
    function showSubmenu(submenuId) {
        document.getElementById(submenuId).style.display = "block";
    }
    

    I changed the handler so it firstly closes all submenus, and then opens the necessary one. Also consider using jQuery or similar library, if you work with JS a lot in your app - it will simplify things a lot.

    P.S. Also you may consider refactoring your code:

    1. Nowadays there is no need to use language attribute for script tag. it's obsolete

    2. use var when declare local variables. explanation