The Intersection Observer API: Practical Examples

This article demonstrates using the Javascript Intersection Observer API, instead of measuring scroll position, to perform common visibility detection tasks.

The Problem

In Javascript, performing an action when an element becomes visible to a user has previously always required the following:

  1. Detecting the current scroll position. Setting an event listener to do this is easy enough, but the performance overhead can be costly. You will almost always want to write a throttling function to limit the amount of events fired when a user is scrolling. If you don’t know how to write this yourself, then you might reach for a library like Lodash, etc. which adds another dependency to your codebase.
  2. Getting the top offset. Select the element you want to observe in the DOM and get its top offset relative to the element (or viewport) you are detecting. This may seem straightforward until you factor in any lazy loaded or async loaded content. Once you finally have that number, don’t forget to recalculate it because that pesky banner image loaded in at the last second and skewed your original number.
  3. Unset and cleanup. Once you run your logic, you need to remember to remove the event listener. Sometimes you may have several.
  4. Beware of main thread work. The function you pass to the event listener will be running on the main thread, and will be running hundreds or possibly thousands of times until your condition is met, even with the throttling you hopefully put in place.
  5. Other use cases. Last but not least, there are scenarios where you may want to detect when an element is about to become visible, or after a user has scrolled past an element by a certain threshold. This would require more changes to the logic above.

The Solution

The Intersection Observer API is an excellent solution to this problem. It’s a fairly recent browser API that lets developers hand most of these tasks off to the browser, in a way that is more optimized.

For more info, click here

Old techniques are here;

https://demos.flesler.com/jquery/scrollTo/

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect