Created
April 21, 2023 08:46
-
-
Save stefanoortisi/fa60526b8692a6180cb520defc79fe26 to your computer and use it in GitHub Desktop.
Script to automatically close the mobile menu when the user scroll the page (siraloe.it)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
- siraloe.it | |
Script to automatically close the mobile menu when the user scroll the page | |
*/ | |
document.addEventListener("DOMContentLoaded", () => { | |
const handlers = document.querySelectorAll(".hfe-nav-menu__toggle"); | |
let isOpen = false; | |
if (handlers.length < 2) { | |
return; | |
} | |
const handler = handlers[1]; | |
const observer = new MutationObserver((mutationList) => { | |
mutationList.forEach((mutation) => { | |
const { type, attributeName } = mutation; | |
if (type === "attributes" && attributeName === "class") { | |
if (handler.classList.contains("hfe-active-menu") && !isOpen) { | |
onOpen(); | |
} | |
if (!handler.classList.contains("hfe-active-menu") && isOpen) { | |
onClose(); | |
} | |
} | |
}); | |
}); | |
observer.observe(handler, { attributes: true }); | |
const onOpen = () => { | |
isOpen = true; | |
window.addEventListener("scroll", () => handler.click(), { once: true }); | |
}; | |
const onClose = () => (isOpen = false); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment