惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Security Archives - TechRepublic
Security Archives - TechRepublic
P
Privacy & Cybersecurity Law Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
LINUX DO - 热门话题
C
Cybersecurity and Infrastructure Security Agency CISA
S
Security Affairs
Latest news
Latest news
Security Latest
Security Latest
N
News and Events Feed by Topic
Spread Privacy
Spread Privacy
P
Proofpoint News Feed
T
The Blog of Author Tim Ferriss
Y
Y Combinator Blog
Google DeepMind News
Google DeepMind News
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
The Exploit Database - CXSecurity.com
The Last Watchdog
The Last Watchdog
C
Cyber Attacks, Cyber Crime and Cyber Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
V
Vulnerabilities – Threatpost
Hacker News - Newest:
Hacker News - Newest: "LLM"
Microsoft Azure Blog
Microsoft Azure Blog
V
Visual Studio Blog
The Cloudflare Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
G
GRAHAM CLULEY
博客园_首页
S
Secure Thoughts
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
AWS News Blog
AWS News Blog
腾讯CDC
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The Register - Security
The Register - Security
N
News and Events Feed by Topic
A
Arctic Wolf
MongoDB | Blog
MongoDB | Blog
爱范儿
爱范儿
Project Zero
Project Zero
A
About on SuperTechFans
罗磊的独立博客
云风的 BLOG
云风的 BLOG
Know Your Adversary
Know Your Adversary
S
Security @ Cisco Blogs
Google Online Security Blog
Google Online Security Blog
K
Kaspersky official blog
L
LINUX DO - 最新话题
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
F
Fortinet All Blogs

Maxime Heckel's Blog

On Rendering the Sky, Sunsets, and Planets - The Blog of Maxime Heckel Shades of Halftone - The Blog of Maxime Heckel Field Guide to TSL and WebGPU - The Blog of Maxime Heckel On Shaping Light: Real-Time Volumetric Lighting with Post-Processing and Raymarching for the Web - The Blog of Maxime Heckel Speaking at Figma Config 2025 - The Blog of Maxime Heckel Post-Processing Shaders as a Creative Medium - The Blog of Maxime Heckel On Crafting Painterly Shaders - The Blog of Maxime Heckel The Art of Dithering and Retro Shading for the Web - The Blog of Maxime Heckel Moebius-style post-processing and other stylized shaders - The Blog of Maxime Heckel Shining a light on Caustics with Shaders and React Three Fiber - The Blog of Maxime Heckel Real-time dreamy Cloudscapes with Volumetric Raymarching - The Blog of Maxime Heckel Painting with Math: A Gentle Study of Raymarching - The Blog of Maxime Heckel Building a magical AI-powered semantic search from scratch - The Blog of Maxime Heckel Beautiful and mind-bending effects with WebGL Render Targets - The Blog of Maxime Heckel Refraction, dispersion, and other shader light effects - The Blog of Maxime Heckel The magical world of Particles with React Three Fiber and Shaders - The Blog of Maxime Heckel The Study of Shaders with React Three Fiber - The Blog of Maxime Heckel Building a Design System from scratch - The Blog of Maxime Heckel Everything about Framer Motion layout animations - The Blog of Maxime Heckel Building a Vaporwave scene with Three.js - The Blog of Maxime Heckel Cubic Bézier: from math to motion - The Blog of Maxime Heckel First steps with GPT-3 for frontend developers - The Blog of Maxime Heckel Building the perfect GitHub CI workflow for your frontend team - The Blog of Maxime Heckel Migrating to Next.js - The Blog of Maxime Heckel Static Tweets with MDX and Next.js - The Blog of Maxime Heckel Advanced animation patterns with Framer Motion - The Blog of Maxime Heckel The Power of Composition with CSS Variables - The Blog of Maxime Heckel My first failed SwiftUI project - The Blog of Maxime Heckel Guide to creating animations that spark joy with Framer Motion - The Blog of Maxime Heckel Using Shortcuts and serverless to build a personal Apple Health API - The Blog of Maxime Heckel SEO mistakes I've made and how I fixed them - The Blog of Maxime Heckel Going native: SwiftUI from the perspective of a React developer - The Blog of Maxime Heckel Build your own preview deployment service - The Blog of Maxime Heckel The little guide to CI/CD for frontend developers - The Blog of Maxime Heckel Immigrating to the US - The Blog of Maxime Heckel The physics behind spring animations - The Blog of Maxime Heckel Generate screenshots of your code with a serverless function - The Blog of Maxime Heckel How to use Framer Motion with Emotion styled-components - The Blog of Maxime Heckel Data Fetching with NextJS: What I learned - The Blog of Maxime Heckel Learning in public - The Blog of Maxime Heckel Fixing the dark mode flash issue on server rendered websites - The Blog of Maxime Heckel How to fix NPM link duplicate dependencies issues - The Blog of Maxime Heckel Running scheduled cross-browser end-to-end tests on Github CI - The Blog of Maxime Heckel How I built my first custom ESLint rule - The Blog of Maxime Heckel React Lazy: a take on preloading views - The Blog of Maxime Heckel Automated UI accessibility testing with Cypress - The Blog of Maxime Heckel Building a GraphQL wrapper for the Docker API - The Blog of Maxime Heckel Switching off the lights - Adding dark mode to your React app - The Blog of Maxime Heckel Getting started with Typescript on Gatsby - The Blog of Maxime Heckel Rebuilding Redux with Hooks and Context - The Blog of Maxime Heckel Asynchronous rendering with React - The Blog of Maxime Heckel Using Flow generics to type generic React components - The Blog of Maxime Heckel How to efficiently type your styled-components with Flow - The Blog of Maxime Heckel How I got started with Kubernetes on GKE - The Blog of Maxime Heckel React sub-components Part 3: Whitelisting sub-components with flow - The Blog of Maxime Heckel React sub-components Part 2: Using the new Context API - The Blog of Maxime Heckel React sub-components - The Blog of Maxime Heckel Running Golang tests with Jest - The Blog of Maxime Heckel No title No title
Scrollspy demystified - The Blog of Maxime Heckel
Maxime Heckel · 2021-03-09 · via Maxime Heckel's Blog

Many of you have emailed or DM'ed me asking about how I implemented my table of content component, the little list of titles you'll see appear on the left gutter once you scroll a bit more down, and how I manage to highlight in that list the title of the current paragraph in view. Well, by popular demand, I finally took the time to write about this specific piece of code, and also use this as an opportunity to deep dive into the inner workings of the main trick behind it named...

Scrollspy

In this article, we'll analyze together an elegant way to implement a Scrollspy, how to abstract it with a Hook for your React project, and finally, I'll add some tips at the end on how you can integrate it with a markdown or MDX based blog to build a little table of content component similar to mine.

It's all about knowing what's intersecting the viewport

Scrollspy is a "technique" that's used to keep track of the content of the user's viewport and highlight the corresponding navigation item.

There are many ways to implement a Scrollspy, some of them are very complicated and involve a lot of maths. But you know me, I always prefer simple yet elegant solutions when it comes to tackling UI-related problems; it's just more satisfying that way ✨. In this case, that elegant solution is called the Intersection Observer API.

What is the Intersection Observer API?

In a nutshell, it's a little tool that you can use in your Javascript frontend code to detect whether a given DOM Node intersects with the document's viewport or another parent element.

How can it be used in the context of a Scrollspy?

As mentioned above, the aim of a Scrollspy is being able to keep track of what's currently "in view" for the user, thus what's intersecting with the viewport. In this blog post right now, if your window is big enough to display the table of content, you should see that the title It's all about knowing what's intersecting the viewport being highlighted since its corresponding part is currently "in view". This is because the DOM element wrapping this first part is currently "intersecting" with our viewport, and also because I built my table of content component to highlight the title corresponding to whichever section is intersecting.

Sounds pretty straightforward so far right? Well, it because that's pretty much all there is behind this kind of implementation of a Scrollspy. However, there can be more nuances such as:

  1. What if 2 elements intersect at the same time? Should we highlight both corresponding titles?

  2. How to take into account something like a fixed header?

Regarding the first question, the implementation I introduce here only considers that one section can be highlighted at a time, thus the first section to intersect will be the one highlighted.

To answer the second one, we're lucky: the Intersection Observer API allows us to pass a rootMargin option. This option adds margins around the root element/the viewport, before computing whether a section is intersecting or not.

For example, adding a rootMargin of "-100px 0px 0px 0px" will add a margin top for our viewport of -100px thus making the intersection of a given element end 100px "earlier".

To help visualize these 2 nuances listed above, I built this little widget below:

  • The mini browser lets you scroll a mock web page with different sections.

  • Each section will be highlighted whenever it intersects with the viewport using the Intersection Observer API.

  • You can modify the "offset" or rootMargin by adding some negative margin-top to see the intersection between the section and the viewport start/end earlier the more offset you add.

  • You can modify the height of the sections to see how the first section in view is always the one being highlighted.

Why use this rather than a scroll event and detecting if the element's scroll position fits in the viewport?

Well, there are 2 main reasons behind that:

  1. Performance: scroll event listeners run on the main thread whereas Intersection Observers do not. Thus using scroll events to continuously keep track of the current section in view is less performant and you'd probably end up needing to add some kind of throttling mechanism. @AggArvanitakis covers this in-depth in his blog post comparing both Intersection Observers and Scroll event performance.

  2. Finding if an element's scroll position fits within the viewport requires ~~a bit of~~ maths and I didn't like it 🤢. You can see by yourself with the code snippet below which is way harder to parse than what we're about to see.

Implementation of isInView, a function that returns true if an element is in view

1

const isInView = (element: Element, offset: number = 0) => {

2

const rect = element.getBoundingClientRect();

5

document.documentElement.scrollTop || document.body.scrollTop;

7

const scrollBottom = scrollTop + window.innerHeight;

9

const elemTop = rect.top + scrollTop;

10

const elemBottom = elemTop + element.offsetHeight;

13

elemTop < scrollBottom - offset && elemBottom > scrollTop + offset;

Abstracting the implementation in a React Hook

Now that we've taken a look at how we can leverage the Intersection Observer API to implement a Scrollspy, let's abstract all the implementation details in a little React Hook so it can be easily used in any current or future project.

First steps with Intersection Observers

Let's take a look at the code necessary to instantiate a new Intersection Observer in Javascript and have it observe a set of elements:

Basic usage of the Intersection Observers API

1

const observer = new IntersectionObserver((entries) => {

2

entries.forEach((entry) => {

3

console.log(entry.isIntersecting);

4

console.log(entry.intersectionRatio);

8

const targetElements = document.querySelectorAll('section');

10

observer.observe(targetElements);

As you can see, there're 2 main things to do to get started:

  1. Create the Intersection Observer and pass a callback function to it. That callback takes 2 arguments entries and observer but we only need to use the first one in our use-case. Entries is an array of objects where each object describes the intersection of one of the elements that we're observing.

  2. Start observing 🔍! For that, we need to create an array of elements to observe and call observer.observe(...).

That's it! You now know how to use the Intersection Observer API to observe how a set of elements intersects with the viewport 🎉!

Building an efficient Hook

I'm sure there are many ways to abstract this but building an efficient Hook and avoid instantiating Intersection Observers all over the place can be pretty challenging.

First, we need to create our Intersection Observer as we did above and wrap it in a useRef Hook. This way we can keep track of the state of any intersection across rerenders and also if we were to update our Intersection Observer, we would not trigger a rerender.

The second key step for our Hook implementation is to know when we should start observing. For that, we can use useEffect so we can start observing as soon as the component using our Hook mounts:

First iteration of our useScrollspy Hook

1

const useScrollspy = (elements: Element[]): [number] => {

2

const observer = React.useRef<IntersectionObserver>(

3

new IntersectionObserver((entries) => {

5

const indexOfElementIntersecting = entries.findIndex((entry) => {

7

return entry.intersectionRatio > 0;

14

React.useEffect(() => {

16

elements.forEach((element) => observer.current.observe(element));

19

return () => observer.current.disconnect();

This works perfectly, but a few things could go wrong:

  1. accessing current directly as we do here to observe and disconnect our Intersection Observer is not safe. The current we access on mount is not guaranteed to be the same when unmounting (remember, we can update the ref without triggering a rerender).

  2. if we were to change the target elements our effect will run again and we'll start keeping track of the new elements which is great! But... we didn't stop keeping track of the older elements (since we didn't unmount). Thus to avoid this scenario from breaking our app, the best thing to do is to check for any existing Intersection Observers currently instantiated and disconnect them every time our effect runs:

Improved version of our useScrollspy Hook handling unwanted side effect

1

const useScrollspy = (elements: Element[]): [number] => {

2

const observer = React.useRef<IntersectionObserver>(

3

new IntersectionObserver((entries) => {

5

const indexOfElementIntersecting = entries.findIndex((entry) => {

7

return entry.intersectionRatio > 0;

14

React.useEffect(() => {

15

const { current: ourObserver } = observer;

17

ourObserver.disconnect();

20

elements.forEach((element) => ourObserver.observe(element));

23

return () => ourObserver.disconnect();

Great, we're almost there! The last step now is to set what to return! For simplicity here, we're only going to return the index of the target currently intersecting with the viewport.

For that, we can initiate a new state to keep track of the index of the target currently intersecting, and set that state accordingly in the callback of our Intersection Observer:

Implementation of useScrollspy returning the index of the current target intersecting

1

const useScrollspy = (elements: Element[]): [number] => {

3

currentIntersectingElementIndex,

4

setCurrentIntersectingElementIndex,

5

] = React.useState(-1);

7

const observer = React.useRef<IntersectionObserver>(

8

new IntersectionObserver((entries) => {

10

const indexOfElementIntersecting = entries.findIndex((entry) => {

12

return entry.intersectionRatio > 0;

16

setCurrentIntersectingElementIndex(indexOfElementIntersecting);

20

React.useEffect(() => {

21

const { current: ourObserver } = observer;

23

ourObserver.disconnect();

26

elements.forEach((element) => ourObserver.observe(element));

29

return () => ourObserver.disconnect();

33

return [currentIntersectingElementIndex];

A few things to note here:

  • using findIndex will return the index of the first target intersecting.

  • we set this index in a local state in that hook. Even though we may be calling set state over and over in that callback it will not impact performance since most of the time we'll be setting the same value that is already in the state.

Handling offsets and custom settings

Our Hook is now almost operational! One last thing to take into account is to have the ability to pass a custom root element and a custom root margin:

  • we need the first one so I can set a custom parent element that is not the main viewport, like for the playground below 😛 (it might also come in handy for you in the future)

  • we need the second one to allow our ScrollSpy to handle offset such as a header as we saw in the widget in the first part of this blog post.

Here's how I abstracted them:

Implementation of useScrollspy with options

9

currentIntersectingElementIndex,

10

setCurrentIntersectingElementIndex,

11

] = React.useState(-1);

13

const rootMargin = `-${(options && options.offset) || 0}px 0px 0px 0px`;

15

const observer = React.useRef<IntersectionObserver>(

16

new IntersectionObserver(

19

const indexOfElementIntersecting = entries.findIndex((entry) => {

21

return entry.intersectionRatio > 0;

25

setCurrentIntersectingElementIndex(indexOfElementIntersecting);

28

root: (options && options.root) || null,

However, we now have a little problem: changing those options won't update our Intersection Observer 😱! But don't worry, working around this problem does not require too many changes:

  • Instead of creating our ref with our Intersection Observer, we simply set it as null first

  • Then, after disconnecting any pre-existing Intersection Oservers, we create a new one with the current set of options and point the current value of the ref to it.

  • We make sure to pass the options in the dependency array of our useEffect Hook so any change in options will disconnect the old observer and create a new one with the latest set of options.

Final implementation of useScrollspy

7

): [number, Element[], number[]] => {

9

currentIntersectingElementIndex,

10

setCurrentIntersectingElementIndex,

11

] = React.useState(-1);

13

const rootMargin = `-${(options && options.offset) || 0}px 0px 0px 0px`;

15

const observer = React.useRef<IntersectionObserver>();

17

React.useEffect(() => {

18

if (observer.current) {

19

observer.current.disconnect();

22

observer.current = new IntersectionObserver(

25

const indexOfElementIntersecting = entries.findIndex((entry) => {

27

return entry.intersectionRatio > 0;

31

setCurrentIntersectingElementIndex(indexOfElementIntersecting);

34

root: (options && options.root) || null,

40

const { current: ourObserver } = observer;

43

elements.forEach((element) =>

44

element ? ourObserver.observe(element) : null

47

return () => ourObserver.disconnect();

48

}, [elements, options, rootMargin]);

50

return [currentIntersectingElementIndex];

It's now time to try out our new shiny Hook! Below you will find a playground containing the implementation of useScrollspy used to highlight the title of the corresponding section in view! (just like my table of content component)

To see our Hook in action you can:

  • scroll up and down the scrollable section in the playground and see the table of content component highlighting the proper title

  • try to modify the offset option

  • try to add or remove sections and see the Scrollspy updating accordingly.

Markdown and MDX integration

We did it! 🎉 We now know how to implement a Scrollspy using Intersection Observer in a React Hook and how to leverage the output of the Hook to highlight the title of the current section "in-view"!

However, we only know how to do this for an arbitrary set of sections in a document. How shall we handle use-cases, like a blog post layout for instance, where we don't know the content/section we'll have to track?

I was facing this challenge myself not long ago. Each post of my blog is an individual Markdown/MDX file with raw text and maybe a bit of markup. I didn't want to hardcode the sections that my Scrollspy needed to track for each blog post:

  • It would be one extra thing to think about before releasing a new article.

  • I'd have to remember to update the set of sections every time I'd update a blog post.

My solution to this: sectionize my content with remark plugins

If you've built a Markdown/MDX-based blog before you've probably heard about remark. It's a little markdown processor that has a lot of plugins to automate some transformations in your markdown/MDX files.

I'm using remark here to automatically "sectionize" my Markdown/MDX posts with the help of 2 plugins:

  • remark-slug: This plugin parses your markdown file to find any h1, h2, h3 element you may have in your markdown, "slugifies" the text within that element, and adds it as an id.

  • a modified version of remark-sectionize: This plugin parses your markdown and will sectionize each part by wrapping both titles and the corresponding content under them in a <section/> tag. You can find the original implementation here. My version is slightly different as not only it will sectionize but it will also add an id tag to the section:

Modified version of remark-sectionize

3

function sectionize(node, ancestors) {

4

const id = node.data.id;

I then added both plugins in my Markdown processor pipeline and magic 🪄 the output generated was exactly what was needed:

9

<section id="my-awesome-content-section">

10

<h2 id="my-awesome-content">My awesome content</h2>

11

<p>Some code, some text</p>

By clicking on the checkbox below, you can highlight the <section/> tags from this blog post, thus visualizing how I sectionize with this method my own blog posts. Try to scroll up and down the post and see how the table of content updates depending on which section is in view!

Highlight the <section/> tags of this post

Wiring up everything

Now it was time to wire everything up. The last thing I needed was to get the ids of the sections and pass them to the Hook. There were multiple ways I could have proceeded:

  • Doing it at build time: use some regex magic to get all those ids and pass them in the frontmatter of my markdown, complex but reliable.

  • Doing it at render time: on mount query all <section/> elements in the document, get the ids and set them in a local state, easy but hacky.

For now I chose the second option:

Example of usage of useScrollspy in an Markdown/MDX based blog post layout

1

const BlogPost = () => {

2

const [ids, setIds] = React.useState<Array<{ id: string; title: string }>>(

6

React.useEffect(() => {

7

const titles = document.querySelectorAll('h2');

8

const idArrays = Array.prototype.slice

10

.map((title) => ({ id: title.id, title: title.innerText })) as Array<{

22

const [currentActiveIndex] = useScrollspy(

24

(item) => document.querySelector(`section[id="${item.id}-section"]`)!

26

{ offset: YOUROFFSET }

But Maxime, I want to build the same table of content as you did

What about the progress bar next to your table of content? I want the same as you!

I hope this blog post brought some light on what a Scrollspy is, Intersection Observers, and also how I implemented my table of content components that so many of you seem to like so much (thank you all for the overall compliments on my blog by the way, I really appreciate them 😄).

If you have any questions, suggestions, or if something in my codebase isn't clear enough, do not hesitate to reach out! I'm always looking for ways to improve the way I write React components and set a good example for other frontend developers.