0

I have been working some code, where I use Hamburger responsive menu. The menu opens and closes when clicked on the hamburger icon. I wanted to add a functionality for closing the menu when clicked outside the menu. I managed to close the menu when clicked outside but without the close animation.

Here is the JS code that I tried:

   $(document).on("click", function () {
      $(".navbar-collapse").removeClass("show");
    });

and the HTML code:

<nav class="navbar navbar-expand-lg tm-navbar" id="tmNav">
    <div class="container">
      <button
        class="navbar-toggler"
        type="button"
        data-toggle="collapse"
        data-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent"
        aria-expanded="false"
        aria-label="Toggle navigation"
      >
        <i class="fas fa-bars navbar-toggler-icon"></i>
      </button>

 <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item">
            A
          </li>
          <li class="nav-item">
            B
          </li>
          <li class="nav-item">
            C
          </li>
          <li class="nav-item">
            D
          </li>            
        </ul>
      </div>

The above JS code closes the menu when clicked outside the menu but without the animations. I would like to close the menu with the closing animation. Would appreciate some help with this issue.

Joskaa
  • 151
  • 1
  • 2
  • 9

1 Answers1

1

If this is Bootstrap's Collapse component (which it looks like considering the collapse and navbar-collapse classes), you don't want to remove the show class yourself. As you found out, that will skip all the other work Bootstrap does; including animating the transition.

Instead, use the provided .collapse('hide') event to cause Bootstrap to close the Collapse for you.

$(document).on('click', function () {
    $('#navbarSupportedContent').collapse('hide');
});
D M
  • 5,769
  • 4
  • 12
  • 27