I'm building a mega menu that has a close button on each menu that works great. However I need to write some JavaScript that says, 'if you click outside a mega menu when it's open, close it'.
I've written a script below. It does detect when a user clicks inside of the mega menu, but it doesn't when they click outside of it. In this case, removing the display-on
class which makes an element have display: block;
.
const dropDownMenu = document.getElementsByClassName("drop-down");
for (let i = 0; i < dropDownMenu.length; i ) {
dropDownMenu[i].addEventListener("click", (e) => {
// If clicking in any area that has drop-down class, do nothing.
if (dropDownMenu[i].contains(e.target)) {
console.log("clicked in mega menu area");
// If clicking in any area outside drop-down class, remove display-on class which closes the menu.
} else {
console.log("clicked outside mega menu area");
document.querySelector(".display-on").classList.remove("display-on");
}
});
}
Working demo if needed can be seen here.
Thanks.
CodePudding user response:
From the above comment ...
"Of cause the OP needs to register the handling of "out of drop-down" events also outside of any
drop-down
classified element.document.body
might be the right element for listening."
... something like this ...
function handleDropDownMenuBehavior(evt) {
if (evt.target.closest('.drop-down') === null) {
document.querySelector(".display-on").classList.remove("display-on");
console.log("clicked outside mega menu area");
} else {
console.log("clicked in or at mega menu area");
}
}
document.body.addEventListener('click', handleDropDownMenuBehavior);
CodePudding user response:
You could add a global event listener to the document which checks if what was clicked on isn't the mega menu. let me know if you need any extra help :)
document.onclick = (e) => {
if (e.target.contains(document.getElementsByClassName("drop-down")[0])) {
console.log('close mega menu');
document.getElementsByClassName("drop-down")[0].classList.remove("display-on");
}
}