IntersectionObserver: Linking Headings and Navigation

A compact educational demo inspired by the article's core idea: watch headings as they enter a scroll area, then update the matching table-of-contents link without continuously calculating every heading position.

1. Basic Observer: Highlight the Heading That Enters View

Code:
Result:
Scroll the article pane threshold: 0.55

Opening Idea

Documentation pages often need a table of contents that follows the reader's current position.

Observer API

IntersectionObserver reports when watched elements intersect with a root viewport or scroll container.

Scroll Use Cases

Lazy loading, infinite lists, and navigation highlighting are natural fits for intersection changes.

Notes

This first version is intentionally small: if a heading is sufficiently visible, its link becomes active.

2. rootMargin: Watch Only the Middle Band

Code:
Result:
Dashed band marks the active detection area rootMargin: -33% 0% -33% 0%

First Heading

The observer's root area is shrunk so headings activate around the middle of the scroll container.

Middle Detection

Negative top and bottom margins make the active zone smaller than the full scroll viewport.

Reduced Work

The browser tells us when a heading crosses the zone, so we avoid constantly comparing positions.

Edge Cases

First and last headings can be tricky when the active zone is too narrow.

3. Entry Data: Show Intersection Ratio in Real Time

Code:
Result:
Scroll until the card crosses the viewport thresholds: 0% to 100%
isIntersecting false
intersectionRatio 0.00
Observed Element

4. Reverse Entries and Unactivate Leaving Headings

Code:
Result:
Scroll slowly; active headings hand off as they leave no scroll event listener

Initial State

When several headings are visible, processing entries in reverse keeps the earlier heading active first.

Leaving View

If the active heading exits the observed area, it is unactivated so another visible heading can take over.

Reverse Order

The callback handles changed entries from bottom to top, matching the article's key implementation insight.

Stable Highlight

The demo keeps navigation state linked to IntersectionObserver changes only.

5. smartNav: Generate Navigation from Headings

Code:
Result:
Links are created from the h3 text click links or scroll

Choose headings

The helper accepts a selector or a NodeList, then builds one link for each heading.

Create links

Each generated link points to the heading id and uses the heading text as its label.

Observe headings

IntersectionObserver updates the active class when a heading enters the reading pane.

Navigate quickly

Clicking a generated link scrolls the article pane to the matching heading.