Fixed bugs with sidenav

This commit is contained in:
alexjanousekGSA
2025-01-10 16:06:55 -04:00
parent 168d93a170
commit 817477bd72
4 changed files with 47 additions and 29 deletions

View File

@@ -1,42 +1,57 @@
document.addEventListener('DOMContentLoaded', () => {
const sidenavItems = document.querySelectorAll('.usa-sidenav__item > .parent-link');
let lastPath = window.location.pathname;
let debounceTimeout = null;
sidenavItems.forEach((link) => {
const parentItem = link.parentElement;
const hasChildren = parentItem.querySelector('.usa-sidenav__sublist');
const currentUrl = window.location.pathname;
const sublist = parentItem.querySelector('.usa-sidenav__sublist');
const targetHref = link.getAttribute('href');
if (
link.getAttribute('href') === currentUrl ||
currentUrl.startsWith(link.getAttribute('href'))
) {
// initialize the menu to open the correct submenu based on the current route
if (window.location.pathname.startsWith(targetHref)) {
parentItem.classList.add('open');
link.setAttribute('aria-expanded', 'true');
}
link.addEventListener('click', (event) => {
if (hasChildren) {
const currentPath = window.location.pathname;
// prevent default behavior only if navigating to the same route
if (currentPath === targetHref) {
event.preventDefault();
return;
}
const isOpen = parentItem.classList.contains('open');
document.querySelectorAll('.usa-sidenav__item.open').forEach((item) => {
if (item !== parentItem) {
item.classList.remove('open');
item.querySelector('.parent-link').setAttribute('aria-expanded', 'false');
}
});
if (!isOpen) {
if (sublist && !parentItem.classList.contains('open')) {
// debounce the menu update to avoid flickering
clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(() => {
parentItem.classList.add('open');
link.setAttribute('aria-expanded', 'true');
} else {
parentItem.classList.remove('open');
link.setAttribute('aria-expanded', 'false');
}
window.location.href = link.getAttribute('href');
}, 50);
}
});
});
// handle browser back/forward navigation
window.addEventListener('popstate', () => {
const currentPath = window.location.pathname;
// sync menu state
sidenavItems.forEach((link) => {
const parentItem = link.parentElement;
const targetHref = link.getAttribute('href');
if (currentPath.startsWith(targetHref)) {
parentItem.classList.add('open');
link.setAttribute('aria-expanded', 'true');
} else {
parentItem.classList.remove('open');
link.setAttribute('aria-expanded', 'false');
}
});
lastPath = currentPath;
});
});