Bootstrap 3 vertical menu with toggable submenus

Gustavo picture Gustavo · Nov 13, 2014 · Viewed 68.8k times · Source

Using Bootstrap 3, I need to construct a vertical menu containing toggable submenus. I have the following structure:

<nav>
    <ul>
        <li><a href="#">Item 1</a></li>
        <li><a href="#">Item 2 (toggle)</a>
            <ul>
                <li><a href="#">Item 2.1</a></li>
                <li><a href="#">Item 2.2</a></li>
                <li><a href="#">Item 2.3</a></li>
            </ul>
        </li>
        <li><a href="#">Item 3</a></li>
        <li><a href="#">Item 4</a></li>
    </ul>
</nav>

I want the UL inside "Item 2" to be hidden by default and unhide/hide it by pressing "Item 2".

Answer

Gustavo picture Gustavo · Nov 13, 2014

The key of making a vertical submenu toggable is to use the attribute data-toggle="collapse" instead of the most common used in navs data-toggle="dropdown".

I prepared this jsfiddle example, and this is the wordking code:

<nav>
    <ul class="nav">
      <li><a href="#">Link 1</a></li>
    <li><a href="#" id="btn-1" data-toggle="collapse" data-target="#submenu1" aria-expanded="false">Link 2 (toggle)</a>
      <ul class="nav collapse" id="submenu1" role="menu" aria-labelledby="btn-1">
        <li><a href="#">Link 2.1</a></li>
        <li><a href="#">Link 2.2</a></li>
        <li><a href="#">Link 2.3</a></li>
      </ul>
    </li>
    <li><a href="#">Link 3</a></li>
    <li><a href="#">Link 4</a></li>
  </ul>
</nav>