Skip to content

Instantly share code, notes, and snippets.

@stefanoortisi
Created April 21, 2023 08:46
Show Gist options
  • Save stefanoortisi/fa60526b8692a6180cb520defc79fe26 to your computer and use it in GitHub Desktop.
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)
/*
- 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