A web component for sticky-positioned page anchor navigation. It observes which section of a page is visible, sets an aria-current
attribute on the active link element, and animates a marker indicator over to it. Check it out on the demo page. 👀
- Uses the FLIP technique to animate marker position.
- The marker element is configurable through CSS custom properties (or directly with CSS, go nuts).
- If a menu item is obscured in the viewport overflow horizontally, it will be scrolled fully into view once active.
- Configure intersection observer options with
observer-root
,observer-root-margin
andobserver-threshold
attributes if it's necessary. - Available as a WebC component for use in 11ty + WebC projects.
scrollspy-nav.css
adds some baseline styles to set up the horizontal menu and overflow scrolling. Include this with the page styles.- Add
scrollspy-nav.js
to the bundle. - or import it as a WebC component into a project.
Wrap a list of anchor links with the <scrollspy-nav>
custom element.
<scrollspy-nav role="navigation" aria-label="Page section navigation">
<ul>
<li>
<a href="#section-1">Section one</a>
</li>
<li>
<a href="#section-2">Section two</a>
</li>
<li>
<a href="#section-3">Section three</a>
</li>
</ul>
</scrollspy-nav>
<article id="section-1"></article>
<article id="section-2"></article>
<article id="section-3"></article>
In the example below, the active link is set once its related section intersects the middle of the viewport.
<scrollspy-nav observer-root-margin="-50% 0%"></scrollspy-nav>
CSS custom properties are available that can change the marker size, color, and position as well as its animation duration and easing. Below is the CSS used on the second <scrollspy-nav>
element from the demo page.
.custom-nav {
--scrollspy-nav-marker-top: 0;
--scrollspy-nav-marker-height: 5px;
--scrollspy-nav-marker-color: royalblue;
--scrollspy-nav-marker-duration: 400ms;
--scrollspy-nav-marker-ease: cubic-bezier(0.34, 1.56, 0.64, 1);
}