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.