Search code examples
jqueryhamburger-menu

Close the hamburger menu when you click outside of container


I want to have a very simple hamburger menu. I'm using jQuery to toggle it to open and close when the hamburger is clicked. But I would like for the user to be able to close it when they click anywhere outside of the div or menu.

The jsfiddle is what I have written out. Don't mind the styling.

I would like to use something like

$(window).on('click', function(){
    $('.responsive-menu').removeClass('expand');
})

But with that added, I cannot even open the menu. Please help. Thank you!


Solution

  • The trick is to check if the element clicked has a parent .responsive-menu or .menu-btn.

    If it has'n any of the two and the menu is expanded, toggle!

    Updated Fiddle

    $(document).on("click", function(e){
      if( 
        $(e.target).closest(".responsive-menu").length == 0 &&
        $(".responsive-menu").hasClass("expand") &&
        $(e.target).closest(".menu-btn").length == 0
      ){
        $('.responsive-menu').toggleClass('expand');
      }
    });