Home > Back-end >  How to close Hamburger menu when clicked outside the menu using Javascript
How to close Hamburger menu when clicked outside the menu using Javascript

Time:04-19

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  id="tmNav">
    <div >
      <button
        
        type="button"
        data-toggle="collapse"
        data-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent"
        aria-expanded="false"
        aria-label="Toggle navigation"
      >
        <i ></i>
      </button>

 <div  id="navbarSupportedContent">
        <ul >
          <li >
            A
          </li>
          <li >
            B
          </li>
          <li >
            C
          </li>
          <li >
            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.

CodePudding user response:

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');
});
  • Related