Skip to content
Advertisement

Bootstrap close responsive menu “on click”

On “PRODUCTS” click I slide up a white div (as seen in attached). When in responsive (mobile and tablet), I would like to automaticly close the responsive navbar and only show the white bar.

I tried:

$('.btn-navbar').click();  

also tried:

$('.nav-collapse').toggle();

And it does work. However in desktop size, it is also called and does something funky to the menu where it shrinks for a second.

Any ideas?

enter image description here

Advertisement

Answer

I’ve got it to work with animation!

Menu in html:

<div id="nav-main" class="nav-collapse collapse">
     <ul class="nav">
         <li>
             <a href='#somewhere'>Somewhere</a>
         </li>
     </ul>
 </div>

Binding click event on all a elements in navigation to collapse menu (Bootstrap collapse plugin):

 $(function(){ 
     var navMain = $("#nav-main");
     navMain.on("click", "a", null, function () {
         navMain.collapse('hide');
     });
 });

EDIT To make it more generic we can use following code snippet

 $(function(){ 
     var navMain = $(".navbar-collapse"); // avoid dependency on #id
     // "a:not([data-toggle])" - to avoid issues caused
     // when you have dropdown inside navbar
     navMain.on("click", "a:not([data-toggle])", null, function () {
         navMain.collapse('hide');
     });
 });
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement