1

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!

Ruby
  • 153
  • 1
  • 2
  • 10
  • 1
    Could we see the rest of your code and how you are integrating those lines please? – Davy M Aug 18 '17 at 02:22
  • Can you elaborate what you mean by "anywhere outside the div"? Would you expect the menu to close if the user clicked a link or button on the page? Have you considered layering an invisible layer with width and height 100%, activating that onclick, then throwing the exposed menu on top of that? – Tony D Aug 18 '17 at 02:30
  • @DavyM The lines are pure css – Ruby Aug 18 '17 at 02:33
  • @TonyD So if the user clicks on the hamburger icon, the menu opens. If they click anywhere on the page, doesn't necessarily have to be a link or button, the menu will close. – Ruby Aug 18 '17 at 02:35
  • this might be helpful? https://stackoverflow.com/questions/8800515/jquery-hide-dropdown-when-clicked-anywhere-but-menu – AJ X. Aug 18 '17 at 02:36

3 Answers3

5

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');
  }
});
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
1

You could add an overlay that is shown and covers your entire page.

You can add the empty markup <div class="overlay"></div> and using css hide it until your hamburger button is clicked. Then if you click the overlay, trigger the button click.

I updated your fiddle: https://jsfiddle.net/nd96f398/2/

lscmaro
  • 995
  • 8
  • 22
0
const navOpen = 
document.getElementById("nav-open);

const navMenu = 
document.getElementById("nav-menu);

document.addEventListener( "click", (e) 
=> {
if(e.target.id !== "nav-open" && 
e.target.id !== "nav-menu") {
nav menu.classList.remove("show");
}
});
Olalekan
  • 1
  • 1