Closing an open collapsed navbar when clicking outside in Booststrap 4

3.5k views Asked by At

I'm currently using Bootstrap 4 and I would like to close a collapsed navbar when clicking outside. It can only be close when you click the toggle button.

Also, there's a problem with the nav-links when I'm clicking the toggle button. After it opens, nav-links are bouncing up. I'm not able to figure out the cause. Kindly please someone help me with my problem. Thank you!

Here's my code:

<body>
 <!--  start navbar -->
 <nav class="navbar navbar-light bg-faded navbar-fixed-top">
  <button class="navbar-toggler hidden-lg-up float-xs-right" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"></button>
    <a class="navbar-brand" href="#"></a>

    <div class="collapse navbar-toggleable-md" id="main-navbar">
      <ul class="nav navbar-nav float-lg-right">
        <li class="nav-item">
          <a class="nav-link" href="#home">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#section-about">About</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#section-portfolio">Portfolio</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#section-contact">Contact</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#resume">Resume</a>
        </li>
      </ul>
    </div>
  </nav>
  <!--   end navbar -->
</body>

Here's my codepen link:

http://codepen.io/marcvs/pen/jVONGM

2

There are 2 answers

3
DokiCRO On BEST ANSWER

Here is solution to your problem:

$(document).ready(function () {
    $(document).click(function (event) {
        var clickover = $(event.target);
        var _opened = $(".collapse").hasClass("collapse in");

        if (_opened === true && !clickover.hasClass("navbar-toggler")) {
            $("button.navbar-toggler").click();
        }
    });
});

Codepen: http://codepen.io/anon/pen/xgbmqr

Its a modified version of this answer

0
wisnia On

I know it's an old topic but I just stumbled upon it and figured I can update the solution a little bit:

$(document).click(event => {
  const isNavbarOpened = $("#navbar.navbar-collapse").hasClass("collapse show");

  // this way, if the navbar is not opened, we don't perform unnecessary operations
  if (isNavbarOpened) {
    const clickedElement = $(event.target);
    const clickedInsideNavbar = clickedElement.closest('nav.navbar').length > 0;

    if (!clickedInsideNavbar) {
      $("button.navbar-toggler").click();
    }
  }
});