Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close an open collapsed navbar when clicking outside of the navbar element in Bootstrap 3?

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(); }); 
like image 424
henrywright Avatar asked May 20 '14 16:05

henrywright


People also ask

How do you close an open collapse navbar when clicking outside the navbar element in bootstrap 4?

Currently, the only way to open or close it is by clicking on the navbar-toggle button.

How do I stop bootstrap navbar from collapsing?

For navbars that never collapse, add the . navbar-expand class on the navbar. For navbars that always collapse, don't add any .

How do I close the menu when I click outside?

Answer: Use the jQuery on() method You can use the jQuery click() method in combination with the on() method to hide the dropdown menu when the user click outside of the trigger element.

How do you collapse a collapsed navbar?

To create a collapsible navigation bar, use a button with class="navbar-toggler", data-toggle="collapse" and data-target="#thetarget" . Then wrap the navbar content (links, etc) inside a div element with class="collapse navbar-collapse" , followed by an id that matches the data-target of the button: "thetarget".


2 Answers

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.

like image 116
nozzleman Avatar answered Sep 22 '22 23:09

nozzleman


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');     } }); 
like image 35
Paul Tarr Avatar answered Sep 24 '22 23:09

Paul Tarr