hugo-theme-hello-friend/source/js/menu.js

52 lines
1.7 KiB
JavaScript
Raw Permalink Normal View History

2019-02-01 10:06:44 +01:00
const container = document.querySelector(".container");
2018-07-20 19:14:22 +02:00
const menu = document.querySelector(".menu");
2019-02-01 10:06:44 +01:00
const mobileMenuTrigger = document.querySelector(".menu-trigger");
const desktopMenu = document.querySelector(".menu__inner--desktop");
const desktopMenuTrigger = document.querySelector(".menu__sub-inner-more-trigger");
const menuMore = document.querySelector(".menu__sub-inner-more");
2018-07-20 19:14:22 +02:00
const mobileQuery = getComputedStyle(document.body).getPropertyValue("--phoneWidth");
const isMobile = () => window.matchMedia(mobileQuery).matches;
const isMobileMenu = () => {
2019-02-01 10:06:44 +01:00
mobileMenuTrigger && mobileMenuTrigger.classList.toggle("hidden", !isMobile());
2018-07-20 19:14:22 +02:00
menu && menu.classList.toggle("hidden", isMobile());
2019-02-01 10:06:44 +01:00
menuMore && menuMore.classList.toggle("hidden", !isMobile());
2018-07-20 19:14:22 +02:00
};
2019-02-01 10:06:44 +01:00
// Common
menu && menu.addEventListener("click", e => e.stopPropagation());
menuMore && menuMore.addEventListener("click", e => e.stopPropagation());
2018-07-20 19:14:22 +02:00
isMobileMenu();
2019-02-01 10:06:44 +01:00
document.body.addEventListener("click", () => {
if (!isMobile() && !menuMore.classList.contains("hidden")) {
menuMore.classList.add("hidden");
} else if (isMobile() && !menu.classList.contains("hidden")) {
menu.classList.add("hidden");
}
});
2018-07-20 19:14:22 +02:00
window.addEventListener("resize", isMobileMenu);
2019-02-01 10:06:44 +01:00
// Mobile menu
mobileMenuTrigger &&
mobileMenuTrigger.addEventListener("click", e => {
e.stopPropagation();
menu && menu.classList.toggle("hidden");
});
// Desktop menu
desktopMenuTrigger &&
desktopMenuTrigger.addEventListener("click", e => {
e.stopPropagation();
menuMore && menuMore.classList.toggle("hidden");
if (menuMore.getBoundingClientRect().right > container.getBoundingClientRect().right) {
menuMore.style.left = "auto";
menuMore.style.right = 0;
}
});