# Multilevel Dropdown

Multilevel dropdowns give you a user friendly way to present a large number of items. The Bootstrap framework doesn't natively support nested dropdowns, but you can achieve this with the help of a bit of custom JavaScript.

You can download the complete example as a bsdesign file.

Download Example

Multilevel Dropdown Example

Note

Note: Although multilevel dropdown are convenient, it is still recommended to use regular dropdowns whenever possible, as they have better usability on mobile devices.

# Creating Multilevel Dropdowns

To create a multilevel dropdown, you need to nest a regular dropdown inside another, as an item in its menu. Just drag and drop these components from the Components panel of the app.

Multilevel Dropdown Overview

Add the following CSS to one of your stylesheets. It will position the nested dropdowns correctly. Note that we added a multilevel class to our dropdown from the attributes panel. This way the code below will affect only dropdowns that are multilevel.

.multilevel .dropdown-menu .dropdown-menu {
  margin-left: 90%;
  margin-top: -30px;
}

Next, we need to write some custom JavaScript, which will make the nested dropdown menus show on mouse hover.

document.addEventListener('DOMContentLoaded', function(){
    // The page has loaded

    let menuItems = document.querySelectorAll('.multilevel .dropdown-menu a');
    
    for (let item of menuItems) {
        // Trigger the menu on click
        item.addEventListener('click', triggerMenu);
        // Trigger the menu on hover. You can remove this.
        item.addEventListener('mouseenter', triggerMenu);
    }
    
    // When the body is clicked, hide all menu items
    
    document.body.addEventListener('click', function() {
        document.querySelectorAll('.multilevel .dropdown-menu .dropdown-menu')
            .forEach(m => m.classList.remove('show'));
    });
});

function triggerMenu(e) {
    
    // Hide all other dropdowns
    e.target.parentNode.querySelectorAll('.dropdown-menu')
        .forEach(m => m.classList.remove('show'));
    
    let toggle = e.target.closest('.dropdown-toggle');
    
    if (!toggle) {
        return;
    }

    // Show the new dropdown menu
    let menu = toggle.nextElementSibling;

    if (menu && menu.matches('.dropdown-menu')) {
        // This is a dropdown menu toggle. Show the menu
        // and prevent it from closing on click.
        menu.classList.add('show');
        e.stopPropagation();
    }
}

You need to copy this code, and paste it in a new JavaScript file in your design. If you download the bsdesign file we've linked in the intro of this article, you don't need to do anything - this code is already included.

With this your multilevel dropdown menus are ready! You can use these dropdowns on their own own, or you can combine them with a Navbar to get a multi level navigation bar for your website.