Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 36 additions & 4 deletions src/layouts/components/Header/components/Navigation.astro
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,10 @@ const { items } = menuTexts[currentLang]
const setActiveMenuItem = (): void => {
const allMenus = mainNav.querySelectorAll('nav > ul')
const currentPathname = window.location.pathname
const currentHash = window.location.hash

// Build the full current URL (without trailing slash in pathname)
const currentFullUrl = currentPathname.replace(/\/$/, '') + currentHash

allMenus.forEach((menu) => {
const menuItems = [...menu.querySelectorAll('a:not([rel*="external"])')] as HTMLAnchorElement[]
Expand All @@ -231,10 +235,17 @@ const { items } = menuTexts[currentLang]
menuItem.classList.remove('is-active')
menuItem.removeAttribute('aria-current')

const itemPathname = menuItem.pathname.replace(/\/$/, '') // Remove trailing slash
const currentPath = currentPathname.replace(/\/$/, '')

if (itemPathname === currentPath || (itemPathname === '' && currentPath === '')) {
// Build the full URL for the menu item
const itemPathname = menuItem.pathname.replace(/\/$/, '')
const itemHash = menuItem.hash || ''
const itemFullUrl = itemPathname + itemHash

// Compare full URLs
if (
itemFullUrl === currentFullUrl ||
(itemFullUrl === '' && currentFullUrl === '') ||
(itemPathname === '' && currentPathname.replace(/\/$/, '') === '')
) {
menuItem.classList.add('is-active')
menuItem.setAttribute('aria-current', 'page')
}
Expand Down Expand Up @@ -474,6 +485,27 @@ const { items } = menuTexts[currentLang]

// Initialize active menu item
setActiveMenuItem()

// Update active menu item when hash changes (for same-page navigation)
window.addEventListener('hashchange', setActiveMenuItem)

// Also listen for popstate (back/forward navigation)
window.addEventListener('popstate', setActiveMenuItem)

// Listen for clicks on menu items to update immediately
const allMenus = mainNav.querySelectorAll('nav > ul')
allMenus.forEach((menu) => {
menu.addEventListener('click', (event) => {
const target = event.target as HTMLElement
const link = target.closest('a') as HTMLAnchorElement
if (link && !link.hasAttribute('rel')) {
// Small delay to ensure URL has changed
setTimeout(() => {
setActiveMenuItem()
}, 10)
}
})
})
})
</script>

Expand Down
Loading