'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 1:[1]
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!
$(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');
}
});
Solution 2:[2]
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/
Solution 3:[3]
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");
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Louys Patrice Bessette |
| Solution 2 | lscmaro |
| Solution 3 | Olalekan |
