Fix for dynamic nav links based on available sections on current page.

This commit is contained in:
Bob Vandevliet 2025-12-18 11:38:23 +01:00
parent 32b9b0e152
commit ff363f50e9

View file

@ -28,15 +28,39 @@ window.addEventListener('pageshow', () =>
document.addEventListener('DOMContentLoaded', () => document.addEventListener('DOMContentLoaded', () =>
{ {
/**
* @type {HTMLDivElement}
*/
const navBar = document.getElementById('navbarNav');
/**
* @type {NodeListOf<HTMLAnchorElement>}
*/
const navLinks = navBar.querySelectorAll('a.nav-link');
/** /**
* @type {NodeListOf<HTMLElement>} * @type {NodeListOf<HTMLElement>}
*/ */
const sectionsWithId = document.querySelectorAll('section[id]'); const sectionsWithId = document.querySelectorAll('section[id]');
// Update nav links and add anchor links to section headers.
sectionsWithId.forEach(anchorTarget => sectionsWithId.forEach(anchorTarget =>
{ {
// Navigate within current page if a section for the anchor exists.
navLinks.forEach(navLink =>
{
const href = navLink.getAttribute('href');
if (href.startsWith('/#') && href.substring(2) === anchorTarget.id)
{
navLink.setAttribute('href', href.substring(1));
}
});
/**
* @type {HTMLHeadingElement|null}
*/
const anchorHeader = anchorTarget.querySelector('h1,h2'); const anchorHeader = anchorTarget.querySelector('h1,h2');
// Add anchor link to section header.
if (anchorHeader) if (anchorHeader)
{ {
const anchorLink = document.createElement('a'); const anchorLink = document.createElement('a');
@ -48,7 +72,7 @@ document.addEventListener('DOMContentLoaded', () =>
}); });
// Collapse the navbar in mobile view after clicking a link. // Collapse the navbar in mobile view after clicking a link.
document.querySelectorAll('#navbarNav li.nav-item>a').forEach(navLink => navLinks.forEach(navLink =>
{ {
navLink.addEventListener('click', () => navLink.addEventListener('click', () =>
{ {