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(); });
Currently, the only way to open or close it is by clicking on the navbar-toggle button.
For navbars that never collapse, add the . navbar-expand class on the navbar. For navbars that always collapse, don't add any .
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.
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".
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.
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'); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With