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

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.

Leave a Comment