Fix for dynamic nav links based on available sections on current page.
This commit is contained in:
parent
32b9b0e152
commit
ff363f50e9
1 changed files with 25 additions and 1 deletions
|
|
@ -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', () =>
|
||||||
{
|
{
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue