How can i make a list menu "collapsible"?

Bruno Charters picture Bruno Charters · Apr 15, 2013 · Viewed 22.7k times · Source

i have a menu with 4 main items and each one having 3 to 5 sub items.

<ul id="navigation">
    <li><a>Diagonóstico</a>

    </li>
    <li class="sub"><a href="javascript:void(0);" class="sub_di1"> › Grátis (na compra de qualquer serviço) </a>

    </li>
    <li><a>Hardware</a> 
    </li>
    <li class="sub"><a href="javascript:void(0);" class="sub_ha1"> › Instalação/Configuração de Componentes</a>

Please check the full code.

As you can see in the jsFiddle, all menu items, when clicked show some text in another div. I put that there just in case it was be needed for further javascript help. What i want is to have all .sub menus collapsed and when i mouseover one of the main ones, it expands the corresponding .sub items so user can see. Thanks!

EDIT:

I managed to get a nice tutorial in one of the comments and came up with THIS!

What i need now is a way to show ALL the .sub menus from the corresponding .main menus instead of only the first ones.

Answer

Jo&#227;o Mosmann picture João Mosmann · Apr 15, 2013

Using only HTML and CSS.

HTML

<ul id="menu">
    <li><a href="SOME_LINK">Some menu without sub-menu</a></li>
    <li><a href="SOME_LINK2">Some menu without sub-menu 2 </a></li>
    <li>Some menu WITH sub-menu
        <ul>
            <li><a href="SOME_LINK">Some sub-menu</a></li>
            <li><a href="SOME_LINK">Some sub-menu 2</a></li>
        </ul>
    </li>
    <li><a href="SOME_LINK3">Some menu without sub-menu 3</a></li>
</ul>

CSS

ul>li>ul{display:none}
ul>li:hover>ul, ul>li:selected>ul{display:block}

JS (jQuery) to OPEN all submenus

$('#menu li>ul').parent().addClass('selected');

JS without Jquery

var menus = document.getElementById('menu').getElementsByTagName('li') 
for(var row in menus){
     if(typeof menus[row] == 'object' && menus[row].getElementsByTagName('ul').length > 0){
         menus[row].getElementsByTagName('ul')[0].className = 'selected';
     }
}