Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to close Hamburger menu when clicked outside the menu using Javascript

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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.

>Solution :

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');
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading