How to close an open collapsed navbar when clicking outside of the navbar element in Bootstrap 3?
Solution 1
Have a look that:
$(document).ready(function () {
$(document).click(function (event) {
var clickover = $(event.target);
var _opened = $(".navbar-collapse").hasClass("navbar-collapse in");
if (_opened === true && !clickover.hasClass("navbar-toggle")) {
$("button.navbar-toggle").click();
}
});
});
Your fiddle works with that: http://jsfiddle.net/52VtD/5718/
Its a modified version of this answer, which lacks the animation and is also a tiny bit more complicated.
I know, invoking the click()
isn't very elegant, but collapse('hide')
did not work for me either, and i think the animation is a bit nicer than adding and removing the classes hardly.
Solution 2
The accepted answer doesn't appear to work correctly. It only needs to check if "navbar-collapse" has the "in" class. We can then fire the collapse method as expected by using our reference to the navbar.
$(document).click(function (event) {
var clickover = $(event.target);
var $navbar = $(".navbar-collapse");
var _opened = $navbar.hasClass("in");
if (_opened === true && !clickover.hasClass("navbar-toggle")) {
$navbar.collapse('hide');
}
});
Solution 3
Using this works for me.
$(function() {
$(document).click(function (event) {
$('.navbar-collapse').collapse('hide');
});
});
Solution 4
The solution I decided to use was taken from the accepted answer here and from this answer
jQuery('body').bind('click', function(e) {
if(jQuery(e.target).closest('.navbar').length == 0) {
// click happened outside of .navbar, so hide
var opened = jQuery('.navbar-collapse').hasClass('collapse in');
if ( opened === true ) {
jQuery('.navbar-collapse').collapse('hide');
}
}
});
This hides an opened collapsed nav menu if the user clicks anywhere outside of the .navbar
element. Of course clicking on .navbar-toggle
still works to close the menu too.
Solution 5
Converted nozzleman's answer for Bootstrap 4(.3.1):
$(document).ready(function () {
$(document).click(
function (event) {
var target = $(event.target);
var _mobileMenuOpen = $(".navbar-collapse").hasClass("show");
if (_mobileMenuOpen === true && !target.hasClass("navbar-toggler")) {
$("button.navbar-toggler").click();
}
}
);
});
Placed in the ngOnInit().
When the document is loaded, this code waits for click events. If the mobile menu dropdown is open (i.e. the collapsible part of the navbar has the "show" class) and the clicked object (target) is not the mobile menu button (i.e. does not have the "navbar-toggler" class), then we tell the mobile menu button it has been clicked, and the menu closes.
Related videos on Youtube
henrywright
I'm a huge WordPress fan and general geek interested in PHP, HTML and CSS. You can usually find me on Twitter @henrywright.
Updated on July 09, 2022Comments
-
henrywright almost 2 years
How can I close an open collapsed navbar on clicking outside of the navbar element? Currently, the only way to open or close it is by clicking on the
navbar-toggle
button.See here for an example and code:
So far, I have tried the following which doesn't seem to work:
jQuery(document).click(function() { }); jQuery('.navbar').click(function(event) { jQuery(".navbar-collapse").collapse('hide'); event.stopPropagation(); });
-
Dmitry Sadakov almost 10 yearsThe 'broken' link in the demo closes when I click outside of the menu; what is broken?
-
henrywright almost 10 years@Paulie_D I've updated my question with what I've tried.
-
henrywright almost 10 years@cDima what broken link are you referring to? I don't see one.
-
Paulie_D almost 10 yearsI'm assuming he means the 'hamburger' element opens the menu at the appropriate width and re-clicking closes it. I assume he wants the same 'close' to take place when clicking anywhere.
-
Paulie_D almost 10 yearsSo just selecting the
body
in your JQuery function should do it, assuming to check to see if THE MENU IS OPEN. -
henrywright almost 10 yearsThe check to see if the menu is open is the part i'm struggling with. Currently, the menu opens and closes when I click outside of the navbar element. I'd like it to just close IF it is already open
-
-
henrywright almost 10 yearsHi @pstenstrm. thanks for this although it doesn't seem to work? I've updated the JSFIDDLE with your jQuery: jsfiddle.net/52VtD/5708
-
pstenstrm almost 10 yearsWell, the
.navbar
is pretty much the entire document in the fiddle. I've updated my answer -
henrywright almost 10 yearsPoint noted! I've given the body a height of 700px so the jsfiddle better illustrates what is happening: jsfiddle.net/52VtD/5709 - the problem now is clicking in the body both closes and opens the dropdown. I need it to close only. Opening should be done only via the toggle button
navbar-toggle
-
henrywright almost 10 yearsYeah, I'm not sure why
collapse('hide)
isn't working. This solution works perfectly though. -
Hiep almost 9 yearsIt won't work if the navbar contains a search box, clicking on the search text input must not close the navbar: jsfiddle.net/duongphuhiep/xtyb6wwu/1
-
davidethell over 8 yearsFor whatever reason I needed this on the latest bootstrap 3: .hasClass("navbar-collapse collapse in")
-
DeFeNdog over 8 yearsYou're missing a closing parenthesis to terminate the click method. });
-
Ebrahim almost 8 yearsthis is very good working when using in angularJS and ui-router. it is very fine to use it on $stateChangeSuccess
-
Jared almost 8 yearsWorked nicely with one change for me. I would make sure that if the user did click somewhere on the open navigation that wasn't a link it would remain open.
-
Bram over 7 yearsHow can you combine this with an input box inside the navbar? Because when I click the input box inside the navbar, the navbar goes away too.
-
wordsforthewise over 7 yearsYeah the accepted answer didn't do anything for me too. This worked.
-
Memj over 7 yearsThank you! I was looking for this for way too long.
-
Amy Barrett over 7 yearsI would change
body
tohtml
to account for tall devices or pages with little content. The body's height matches the content, rather than the visible screen area, so if you have a page with little content, taps below the content area won't trigger. Otherwise a great answer and works really well, even with navbar submenus. -
Dani over 7 yearsWhere can I add this?
-
Rachel S almost 7 yearsworks beautifully. To make it close for any click other than the menu itself and the navbar-toggle button, just replace the first ".navbar" with ".navbar-collapse" so that even if you click other links in the navbar, it will still close the menu.
-
user1127860 over 6 yearsIf using Aurelia you can use it this way
this.eventAggregator.subscribe('router:navigation:success', response => { jQuery("navigation button.navbar-toggle").click(); });
-
Lev Zakharov over 5 yearsPlease, add explanation for your answer.
-
gdfgdfg over 4 yearsI am not sure is
click()
will work on mobiles, where this menu is used. -
Nandostyle over 4 yearsThis worked for me. All other answers are from some years ago and might not work. If you are using Bootstrap 4 as per the guides, this will work
-
Anurag almost 4 yearsI had to remove 'in' class from hasClass check, without which it was not working. May be because I did not have an 'in' class in my .navbar-collapse element. I am using bootstrap 4.
-
towi_parallelism over 3 years
var _opened = $navbar.hasClass("show");
for Bootstrap 5 -
Andre Ricardo Duarte over 3 yearsThank you @Cosmin Staicu to better format my answer.
-
Michal - wereda-net almost 2 yearsThat is right. It works.