Skip to content

Commit 7e66041

Browse files
committed
Add auto-highlight of sidebar items based on sections during scroll.
Closes #144. Closes #145.
1 parent ae030c9 commit 7e66041

1 file changed

Lines changed: 16 additions & 0 deletions

File tree

docs/static/main.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,22 @@ document.addEventListener('DOMContentLoaded', () => {
106106
// Highlight sidebar items.
107107
highlightNav();
108108
window.addEventListener('hashchange', highlightNav);
109+
110+
// Highlight sidebar link based on scroll position in demo sections.
111+
const sections = document.querySelectorAll('.demo-section');
112+
const side = document.querySelector('aside[data-sidebar]');
113+
if (sections.length && side) {
114+
const ob = new IntersectionObserver(items => {
115+
const ok = items.filter(e => e.isIntersecting).sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top)[0];
116+
if (!ok) return;
117+
118+
side.querySelector('[aria-current]')?.removeAttribute('aria-current');
119+
side.querySelector(`a[href$="#${ok.target.id}"]`)?.setAttribute('aria-current', 'page');
120+
}, { rootMargin: '0px 0px -60% 0px' });
121+
122+
// Attach a scroll observer to all sections.
123+
sections.forEach(s => ob.observe(s));
124+
}
109125
});
110126

111127

0 commit comments

Comments
 (0)