I\'m using a Bootstrap responsive navbar. When the navbar is collapsed and I open the menu and click on a menu item, the menu doesn\'t close automatically, and I have to do
Edit: As Maximus points out below, the 3.x bootstrap solution is:
$('.navbar-collapse a').click(function(){
$(".navbar-collapse").collapse('hide');
});
https://jsfiddle.net/yohuLuj2/
Old Answer for 2.x bootstrap:
You should be able to do that by adding a click handler to the list items and then closing the nav that way.
$('.nav-collapse').click('li', function() {
$('.nav-collapse').collapse('hide');
});
Heres a jsfiddle: http://jsfiddle.net/hajpoj/By6ym/4/
Just remember to traverse up the DOM tree and close the associated Navbar, and not all Navbars. In particular for Bootstrap 3, use something similar to the following code snippet:
$("body").on("click", ".navbar-collapse a", function() {
var $this = $(this);
setTimeout(function() {
$this.closest(".navbar-collapse").collapse('hide');
}, 350);
});
Another problem is when you see the navbar on desktop, it try to hide/show the navbar, so I made this:
$('.navbar-collapse a:not(.dropdown-toggle)').click(function(){
if($(window).width() < 768 )
$('.navbar-collapse').collapse('hide');
});
Simply put this code in main.js
$(document).on('click', '.navbar-collapse.in', function (e) {
if ($(e.target).is('a')) {
$(this).collapse('hide');
}
});
My problem was, I was creating single page layout with anchors. So, when you downsize the window, menu hide on link click perfectly. Thanks to above user who gave me clue. But, when upsize window, the bind event always there (without reloading, though). So, here what I did. Hope it helps someone :)
jQuery.noConflict();
(function($){
$('ul#menu-menu-with-anchors li a, a[href="#top"]').click(function(){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top - ($('body').hasClass('admin-bar') ? 160 : 130)
}, 500);
return false;
});
bindUnbindNavToggle($);
$(window).resize(function(){
bindUnbindNavToggle($);
});
})(jQuery);
function bindUnbindNavToggle($){
if( $('button.navbar-toggle').css('display') != 'none' ) {
$('.navbar-collapse ul li a').on('click', function(){
$('.navbar-collapse').collapse('hide');
return false;
});
}
else {
$('.navbar-collapse ul li a').on('click', function(){
return false;
});
}
}
Only thing I'd add to jason's solution is the exception for dropdowns. You don't want to close your menu if someone is simply clicking to toggle the submenu. So…
$('.navbar-collapse a:not(.dropdown-toggle)').click(function(){
$(".navbar-collapse").collapse('hide');
});