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

106,491

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.

Share:
106,491

Related videos on Youtube

henrywright
Author by

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, 2022

Comments

  • henrywright
    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
      Dmitry Sadakov almost 10 years
      The 'broken' link in the demo closes when I click outside of the menu; what is broken?
    • henrywright
      henrywright almost 10 years
      @Paulie_D I've updated my question with what I've tried.
    • henrywright
      henrywright almost 10 years
      @cDima what broken link are you referring to? I don't see one.
    • Paulie_D
      Paulie_D almost 10 years
      I'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
      Paulie_D almost 10 years
      So just selecting the body in your JQuery function should do it, assuming to check to see if THE MENU IS OPEN.
    • henrywright
      henrywright almost 10 years
      The 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
    henrywright almost 10 years
    Hi @pstenstrm. thanks for this although it doesn't seem to work? I've updated the JSFIDDLE with your jQuery: jsfiddle.net/52VtD/5708
  • pstenstrm
    pstenstrm almost 10 years
    Well, the .navbar is pretty much the entire document in the fiddle. I've updated my answer
  • henrywright
    henrywright almost 10 years
    Point 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
    henrywright almost 10 years
    Yeah, I'm not sure why collapse('hide) isn't working. This solution works perfectly though.
  • Hiep
    Hiep almost 9 years
    It 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
    davidethell over 8 years
    For whatever reason I needed this on the latest bootstrap 3: .hasClass("navbar-collapse collapse in")
  • DeFeNdog
    DeFeNdog over 8 years
    You're missing a closing parenthesis to terminate the click method. });
  • Ebrahim
    Ebrahim almost 8 years
    this is very good working when using in angularJS and ui-router. it is very fine to use it on $stateChangeSuccess
  • Jared
    Jared almost 8 years
    Worked 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
    Bram over 7 years
    How 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
    wordsforthewise over 7 years
    Yeah the accepted answer didn't do anything for me too. This worked.
  • Memj
    Memj over 7 years
    Thank you! I was looking for this for way too long.
  • Amy Barrett
    Amy Barrett over 7 years
    I would change body to html 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
    Dani over 7 years
    Where can I add this?
  • Rachel S
    Rachel S almost 7 years
    works 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
    user1127860 over 6 years
    If using Aurelia you can use it this way this.eventAggregator.subscribe('router:navigation:success', response => { jQuery("navigation button.navbar-toggle").click(); });
  • Lev Zakharov
    Lev Zakharov over 5 years
    Please, add explanation for your answer.
  • gdfgdfg
    gdfgdfg over 4 years
    I am not sure is click() will work on mobiles, where this menu is used.
  • Nandostyle
    Nandostyle over 4 years
    This 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
    Anurag almost 4 years
    I 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
    towi_parallelism over 3 years
    var _opened = $navbar.hasClass("show"); for Bootstrap 5
  • Andre Ricardo Duarte
    Andre Ricardo Duarte over 3 years
    Thank you @Cosmin Staicu to better format my answer.
  • Michal - wereda-net
    Michal - wereda-net almost 2 years
    That is right. It works.