webbed-site/menu.js
2024-09-26 16:43:50 -05:00

54 lines
No EOL
2.1 KiB
JavaScript

/* Toggle between showing and hiding the navigation menu links when the user clicks on the hamburger menu / bar icon */
function myFunction() {
var x = document.getElementById("myLinks");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function toggleSubmenu(event) {
event.preventDefault(); // Prevent the default anchor click behavior
var submenu = event.target.nextElementSibling; // Get the submenu
if (submenu.style.display === "block") {
submenu.style.display = "none";
} else {
submenu.style.display = "block";
}
}
// Function to keep the menu open based on the current URL
function setActiveMenu() {
const currentUrl = window.location.pathname; // Get current URL path
const menuItems = document.querySelectorAll('.menu a');
menuItems.forEach(item => {
// Check if the current item is the active one
if (item.getAttribute('href') === currentUrl) {
item.classList.add('active'); // Add active class to the current link
const submenu = item.closest('.submenu'); // Get the closest submenu of this item
// If there's a submenu, show it
if (submenu) {
submenu.style.display = 'block'; // Open the submenu
const parentMenuItem = submenu.previousElementSibling; // Get the parent menu item
if (parentMenuItem) {
parentMenuItem.classList.add('active'); // Highlight the parent item
}
}
} else if (item.closest('.submenu') && item.getAttribute('href') === currentUrl) {
// If this is a submenu item, add active class to the submenu item
item.classList.add('active');
// Find the parent menu item and open the submenu
const parentMenuItem = item.closest('.menu-item');
parentMenuItem.querySelector('.submenu-toggle').classList.add('active'); // Highlight parent item
const parentSubmenu = parentMenuItem.querySelector('.submenu'); // Get the submenu
if (parentSubmenu) {
parentSubmenu.style.display = 'block'; // Open parent submenu
}
}
});
}