I am designing a website and have adapted a simple javascript script to display sub-links under every menu title.
The menu titles are stored in a list and each one houses individual hyperlinks and are revealed using a CSS file with the following classes:
.hidden {display: none;}
.unhidden {display: block;}
Based on this javascript function:
function unhide(liID) {
var item = document.getElementById(liID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
Here is a sample of the HTML file:
<a href="javascript:unhide('menu1');">First Menu</a>
<li id="menu1" class="hidden">
<ul class="subMenus">
<li>Sub menu 1 item 1</li>
<li>Sub menu 1 item 2</li>
<li>Sub menu 1 item 3</li>
<li>Sub menu 1 item 4</li>
</ul>
</li>
<a href="javascript:unhide('menu2');">Second Menu</a>
<li id="menu2" class="hidden">
<ul class="subMenus">
<li>Sub menu 2 item 1</li>
<li>Sub menu 2 item 2</li>
<li>Sub menu 2 item 3</li>
<li>Sub menu 2 item 4</li>
</ul>
</li>
The code works and performs well. But with the way it is coded, once a menu has been opened it must be clicked again for it to collapse. Otherwise the lists get really long and crowded after 3 or 4 menus are opened.
My question is…., what is the code required in the javascript to close the previously opened menu as it opens a new one to save space?
Thanks.
For keeping previous active menu in global variable you can hide previously selected menu, following js may helpful for you
}