If you have a table of contents on a long-scrolling page, thanks to, say, position: fixed;
or position: sticky;
, the IntersectionObserver
API in JavaScript is the perfect companion to highlight items in the table of contents when corresponding content is in view.
Ben Frain has a post all about this:
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.
Compared to older techniques that need to bind to scroll events and perform their own math, this code is shorter, faster, and more logical. If you’re looking for the demo on Ben’s site, the article is the demo. And here’s a video on it:
I’ve mentioned this stuff before, but here’s a Bramus Van Damme version:
And here’s a version from Hakim el Hattab that is just begging for someone to port it to IntersectionObserver
because the UI is so cool:
This is jazzy! I wrote something similar a couple months back. Great post!
this is so good
I’m pretty new to the Intersection Observer API, but porting Hakim’s navbar concept was a nice challenge to get the feel of how it works. Seems to work pretty well: https://codepen.io/agrimsrud/pen/XWNLMeW
Not too many lines of code saved though, so I’m sure someone can come up with an even more efficient version…
I can see why you would want a deeper level on a table of content beause you will like to include everything, but the problem is, if you use h1, h2, h3, h4 it becomes too long a table that it take too long to read, and it should maybe be a PDF instead – or the blog post should be divided into collections of blog posts, such that it resembles chapters in a book.
And also the table will overflow on smaller screens when it gets too long. Remember, that a blog post is not a book. It is something meant to be read quickly. A full table of content with sub level Hx’s should really not be needed, and therefore using only H2’s and making an overview instead of a table of content is easier to get a quick overview over.
I would say, if you cannot sum up the most important content of an H2 in that H2 headline without also including H3 and/or H4, then you might be doing it wrong. Maybe your H2 headline is too unprecise.
I would like to see an argument with POC for going deeper than H2 in the table of content.
Hi there, can anyone tell how can we implement same thing using next.js?