bhttoan
bhttoan

Reputation: 2736

Bootstrap sub menu doesn't close previous submenu when opening another

I am using Bootstrap 3.1.1 and dropdowns - I have built a dropdown menu with sub menus. Each menu opens and closes on click but the problem is that if I open a sub menu and then open another sub menu the first sub menu remains open. I would like any open sub menu to close upon opening another menu.

I am using this for my menu and submenu:

$(document).ready(function() {
    $('.dropdown-toggle').dropdown();

    $('.dropdown-submenu>a').unbind('click').click(function(e){
        $(this).next('ul').toggle();
        e.stopPropagation();
        e.preventDefault();
    });
});

and then my HTML:

<li class="dropdown" id="menu">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Menu <b class="caret"></b></a>
    <ul class="dropdown-menu">
        <li><a href="/item1">Item 1</a></li>
        <li class="dropdown-submenu"><a href="#" data-toggle="dropdown">Submenu 1</a>
            <ul class="dropdown-menu">
                <li><a class="submenu-open" href="/subitem1">Subitem 1</a></li>
            </ul>
        </li>
    </ul>
</li>

How can I make sub menus close on opening another menu?

http://jsfiddle.net/ue7cw513/2/

Upvotes: 1

Views: 2312

Answers (2)

Yusuf Ibrahim
Yusuf Ibrahim

Reputation: 1619

You can just hide other sub menu before open selected menu:

$('.dropdown-submenu>a').unbind('click').click(function(e){
        $('.dropdown-submenu>ul.dropdown-menu').hide();
        $(this).next('ul').toggle();
        e.stopPropagation();
        e.preventDefault();
    });

Upvotes: 2

bhttoan
bhttoan

Reputation: 2736

I figured it out - I just hid all submenu ul on clicking a new sub menu using:

    $('.dropdown-submenu>ul').hide();

so the code now is:

    $('.dropdown-submenu>a').unbind('click').click(function(e){
        $('.dropdown-submenu>ul').hide();
        $(this).next('ul').toggle();
        e.stopPropagation();
        e.preventDefault();
    });

Upvotes: 2

Related Questions