brunodd brunodd - 2 months ago 35
CSS Question

Bootstrap 3 - Navbar with two collapse menus

How can I use two navbar-toggle menus next to each other? If I click on the first icon it will open normally but if I click on the second icon, the first one doesn't close.

Here is what I am trying to do

<nav class="navbar-blue" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header navbar-default">
<button type="button" class="navbar-toggle navbar-user" data-toggle="collapse" data-target="#navbar-collapse-2">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>

<button type="button" class="navbar-toggle navbar-menu" data-toggle="collapse" data-target="#navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>

<a class="navbar-brand" href="#">
Logo goes here
</a>
</div>

<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-default" id="navbar-collapse-1">
<ul class="nav navbar-nav client-nav navbar-right">
<li>
<a class="active" href="#">My Projects</a>
</li>
<li>
<a href="#">Search</a>
</li>
<li>
<a href="#">Post Project</a>
</li>
<li class="hidden-xs">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><span class="fa fa-user"></span><span class="fa fa-sort-desc"></span></a>
<ul class="dropdown-menu client-dropdown">
<li><a href="#">My Profile</a></li>
<li><a href="#">Account Settings</a></li>
<li><a href="#">Sign Out</a></li>
</ul>
</li>
</ul>
</div>

<!-- User menu to show on screens < 768px -->
<div class="collapse navbar-collapse navbar-default" id="navbar-collapse-2">
<ul class="nav navbar-nav client-nav navbar-right">
<li><a href="#">My Profile</a></li>
<li><a href="#">Account Settings</a></li>
<li><a href="#">Sign Out</a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>

Answer

I had to update bootstrap to the latest version. Your demo is using 3.0.0 whereas 3.3.5 is the latest. Regardless, according to the documentation from bootstrap's site, you can accomplish this by listening for the show.bs.collapse event and triggering .collapse('hide') for the other menus.

$(function(){
    $('.navbar-blue .navbar-collapse').on('show.bs.collapse', function(e) {
        $('.navbar-blue .navbar-collapse').not(this).collapse('hide');
    });
});

Demo: Jsfiddle

Comments