Member-only story
Javascript Intersection Observer
The Intersection observer API allows you to determine when and how much of an element is visible inside another element. This new API replaces the scroll handler API in many cases. The top use cases for the intersection observer are:
- Sticky navigation bars
- Live table of contents
- Some scrolling effects
Though a bit more complicated to wrap your head around, the new API performs significantly better than alternate approaches, as measured by percentage of time spent by the browser running JS code in live scrolling scenarios. The alternate approach is performing height and width calculations during scroll handler functions. MDN says about these alternate approaches:
Historically, detecting visibility of an element, or the relative visibility of two elements in relation to each other, has been a difficult task for which solutions have been unreliable and prone to causing the browser and the sites the user is accessing to become sluggish. — Mozilla