hextra/assets/js/menu.js

71 lines
2.2 KiB
JavaScript
Raw Normal View History

// Hamburger menu for mobile navigation
document.addEventListener('DOMContentLoaded', function () {
const menu = document.querySelector('.hamburger-menu');
const overlay = document.querySelector('.mobile-menu-overlay');
const sidebarContainer = document.querySelector('.sidebar-container');
// Initialize the overlay
const overlayClasses = ['hx-fixed', 'hx-inset-0', 'hx-z-10', 'hx-bg-black/80', 'dark:hx-bg-black/60'];
overlay.classList.add('hx-bg-transparent');
overlay.classList.remove("hx-hidden", ...overlayClasses);
function toggleMenu() {
// Toggle the hamburger menu
menu.querySelector('svg').classList.toggle('open');
// When the menu is open, we want to show the navigation sidebar
sidebarContainer.classList.toggle('max-md:[transform:translate3d(0,-100%,0)]');
sidebarContainer.classList.toggle('max-md:[transform:translate3d(0,0,0)]');
// When the menu is open, we want to prevent the body from scrolling
document.body.classList.toggle('hx-overflow-hidden');
document.body.classList.toggle('md:hx-overflow-auto');
}
function hideOverlay() {
// Hide the overlay
overlay.classList.remove(...overlayClasses);
overlay.classList.add('hx-bg-transparent');
}
menu.addEventListener('click', (e) => {
e.preventDefault();
toggleMenu();
if (overlay.classList.contains('hx-bg-transparent')) {
// Show the overlay
overlay.classList.add(...overlayClasses);
overlay.classList.remove('hx-bg-transparent');
} else {
// Hide the overlay
hideOverlay();
}
});
overlay.addEventListener('click', (e) => {
e.preventDefault();
toggleMenu();
// Hide the overlay
hideOverlay();
});
// Select all anchor tags in the sidebar container
const sidebarLinks = sidebarContainer.querySelectorAll('a');
// Add click event listener to each anchor tag
sidebarLinks.forEach(link => {
link.addEventListener('click', (e) => {
// Check if the href attribute contains a hash symbol (links to a heading)
if (link.getAttribute('href') && link.getAttribute('href').startsWith('#')) {
// Only dismiss overlay on mobile view
if (window.innerWidth < 768) {
toggleMenu();
hideOverlay();
}
}
});
});
});