IntersectionObserver Makes Table of Contents Highlighting Effortless

For pages with a fixed or sticky table of contents, the IntersectionObserver API in JavaScript pairs perfectly with it. The API lets you highlight the table of contents item whose corresponding content is currently in view, as Ben Frain details in a new post.

Thanks to IntersectionObserver we have a small but very efficient bit of code to create our table of contents, provide quick links to jump around the document and update readers on where they are in a document as they read.

Older techniques required binding to scroll events and doing your own math. With IntersectionObserver, the code is shorter, faster, and more logical. Frain's article itself doubles as the live demo, and his post also includes a video walkthrough.

This site has covered the approach before, including a variation from Bramus Van Damme. There's also a version from Hakim el Hattab with a UI that is just begging for someone to port it to IntersectionObserver.

Direct Link →