From a7dd83a0133e89a34494acbca8990b01d78cecdd Mon Sep 17 00:00:00 2001 From: rxyhn Date: Mon, 9 Sep 2024 05:16:14 +0700 Subject: [PATCH] fix: header active state --- src/scripts/main.ts | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/scripts/main.ts b/src/scripts/main.ts index a9991df..4558353 100644 --- a/src/scripts/main.ts +++ b/src/scripts/main.ts @@ -55,11 +55,24 @@ window.evaluateHeaderPosition = () => { window.applyMenuItemClasses = () => { const menuItems = document.querySelectorAll("nav a"); - const currentPath = window.location.pathname; + let currentPath = window.location.pathname; + + if (currentPath === "/") { + currentPath = "/"; + } else { + currentPath = currentPath.replace(/\/$/, ""); + } + const activeClass = ["text-white", "font-bold"]; menuItems.forEach((menuItem) => { - if (new URL(menuItem.href).pathname === currentPath) { + let menuItemPath = new URL(menuItem.href).pathname; + + if (menuItemPath !== "/") { + menuItemPath = menuItemPath.replace(/\/$/, ""); + } + + if (menuItemPath === currentPath) { menuItem.classList.add(...activeClass); } else { menuItem.classList.remove(...activeClass);