Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  154] [ 5]  / answers: 1 / hits: 116262  / 10 Years ago, tue, may 20, 2014, 12:00:00

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();
});

More From » jquery

 Answers
5

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.


[#70930] Sunday, May 18, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
julieth

Total Points: 382
Total Questions: 99
Total Answers: 85

Location: Cape Verde
Member since Fri, Nov 27, 2020
4 Years ago
julieth questions
;