With only a few lines, you can vastly improve UX
I came across the Intersection Observer API while learning how Gatsby prefetches links to give the appearance of blazingly fast navigation. I postponed looking into it for a couple of months but finally dove in last weekend.
What Is the Intersection Observer API?
In short, it enables you to detect the visibility of an element, i.e. if it’s in the current viewport, and also the relative visibility of two elements in relationship to each other.
- Lazy loading of images.
- Infinite scrolls.
- Prefetching of links when they appear on the screen (Gatsby does this).
- To detect whether an ad was viewed or not (more tracking).
- To determine whether a user has read an article and to what extent (think medium view vs. read stats).
- To run costly renderings and animations only when they are visible on the screen.
The Technical Stuff
As per usual, the documentation on MDN is great, but I had some trouble figuring out a couple of things and am sharing my notes here for that reason.
At the core of the Intersection Observer API are the following two lines:
var observer = new IntersectionObserver(callback, options);
- First, you create an
- Then, you ask the
- When the desired
callbackfunction is called.
This was the tricky part to understand. Before going through the settings in options, you should have a firm grasp on the following:
Intersection Observer API lets you do something in the callback function when it observes an intersection (beyond a certain threshold) between the root element and the target element.
- Think of
rootas the outer rectangle, or the rectangle within which you want to observe for an intersection.
targetis the element which you are watching.
thresholdgives you the extent to which the overlap should occur.
rootMarginis the margin applied to the root before the extent of the intersection is calculated.
Rules of Thumb
- The API is asynchronous, so use the
callbackfunction to do something when the intersection happens.
rootelement can be decided using the CSS selector.
- If you specify
root: document.querySelector(‘null’), the current viewport of the user will be the
- Play around with
rootMarginto get the exact behavior you are expecting.
This is pretty much the core concept in Intersection Observer API. For further reading, see MDN’s documentation.
While learning this API, I wanted to see if I could create something useful. So, I wrote just a few lines and created a Chrome extension. The extension updates the URL with the ID of the latest section that is visible on the screen.
So, when you share the updated URL with your friends, they can directly go to the section that you were reading. Pretty cool for a few lines written in less than an hour, eh?
The code for this extension is less than 30 lines long.
If you would like to use it, just fork the GitHub code or send me a pull request.