This repository has been archived on 2023-09-28. You can view files and clone it, but cannot push or open issues or pull requests.
homepage/themes/terminal/assets/js/menu.js

45 lines
1.2 KiB
JavaScript

const container = document.querySelector(".container");
const allMenus = document.querySelectorAll(".menu");
// Hide menus on body click
document.body.addEventListener("click", () => {
allMenus.forEach(menu => {
if (menu.classList.contains("open")) {
menu.classList.remove("open");
}
});
});
// Reset menus on resize
window.addEventListener("resize", () => {
allMenus.forEach(menu => {
menu.classList.remove("open");
});
});
// Handle desktop menu
allMenus.forEach(menu => {
const trigger = menu.querySelector(".menu__trigger");
const dropdown = menu.querySelector(".menu__dropdown");
trigger.addEventListener("click", e => {
e.stopPropagation();
if (menu.classList.contains("open")) {
menu.classList.remove("open");
} else {
// Close all menus...
allMenus.forEach(m => m.classList.remove("open"));
// ...before opening the current one
menu.classList.add("open");
}
if (dropdown.getBoundingClientRect().right > container.getBoundingClientRect().right) {
dropdown.style.left = "auto";
dropdown.style.right = 0;
}
});
dropdown.addEventListener("click", e => e.stopPropagation());
});