By · Updated

Scrollspy Navigation

Highlight the Current Section with IntersectionObserver

No ratings yet

OneTask is free, with no sign-up, and built by one person.
If this tool saved you time, a coffee helps keep new ones coming.

How the Scrollspy Navigation works

Scrollspy navigation highlights the link for whichever section is on screen, so a long page always shows readers where they are. Enter section titles, choose a sticky side list or a top bar, and scroll the preview to watch the highlight follow along.

Long single pages such as documentation, product pages and guides are easier to use when the table of contents doubles as a position marker. Readers can see how far through they are and jump straight to any section with one click.

How the scrollspy navigation works

The script uses IntersectionObserver instead of a scroll listener, so the browser does the measuring and nothing runs on every scroll frame. The rootMargin shrinks the watched area to a thin band near the top of the window, and whichever section crosses that band becomes the active one. Its link gets aria-current="true", which screen readers announce and the CSS uses to style it.

Jumping to a section

Every link is a normal #id anchor, so it works with no JavaScript at all. scroll-margin-top stops headings from landing under the sticky bar, and smooth scrolling is only turned on for visitors who have not asked for reduced motion.

FAQ

Why does the highlight change too early or too late?

The rootMargin controls where the switch happens. -10% 0px -80% 0px watches a band from 10% to 20% down the window. Move both numbers down if your sections are short, or if you have a tall sticky header that covers the top of the page.

What happens with very short sections at the bottom?

The last sections may never reach the band if the page cannot scroll that far. Add some bottom padding to the content, roughly the height of the window, or accept that the final link lights up only once the section reaches the band.

Should I use aria-current or a class for the active link?

Use aria-current, because it carries the meaning to assistive technology as well as to the CSS. A class alone only changes the look. The value true suits in-page navigation; page is meant for links to the current page in a site menu.

Does the side layout work on phones?

Below 640 pixels the side column no longer fits, so a media query turns it into a sticky row of links above the content that scrolls sideways. The script does not change, because it only watches the sections.

See also: all UI Components tools, Layout & Spacing, Shadows & Motion, Shapes & SVG, Forms & Inputs, Colour.

Related tools