Once upon a time, developers (myself included) would write scripts to detect if something was in the browser's viewport, and these scripts were more complicated than they needed to be. They'd essentially calculate the distance scrolled, the distance the element is from the top, the height of the element, and then do some math.
Those days are over (can I get a hallelujah?). We now have the Intersection Observer, a native API that introduces an observer that will trigger an update once an observed element goes out of or comes into the viewport. For now, we'll skip the nuances of what the observer model is, and focus on how to use the Intersection Observer.
Let's go over the basic steps of setting up an observer, and then we'll dive into each piece:
- Create our observer
- Get an array of elements to watch and tell our observer to watch each one
- Respond when an element comes into/goes out of the viewport
Step one: let's create our observer. This one is fairly simple, we'll declare a new "IntersectionObserverâ€ class, and pass it a callback and an object with some optional arguments (I won't go over them here, since they aren't important to learning the basics). Here's an example:
[gist src=https://gist.github.com/benrgreene/a5fb2e46009c3c8f2e672037091b6ae4 file=observer.js][/gist]
We'll cover the callback in a second. At the moment, we'll need to grab all our elements we want to watch, and then instruct our observer to watch them. This will use the observer's "observe" method. Very clever name that. Here's my example:
[gist src=https://gist.github.com/benrgreene/a5fb2e46009c3c8f2e672037091b6ae4 file=observe.js][/gist]
From there, the observer is watching our elements and will let us know when they enter OR leave the viewport.
Now, we need our callback. This function is going to need to take two parameters:
- entries: this will be an array of objects. Each object will have a couple useful things, one being a boolean called "isIntersecting" which tells us if the entry is in the viewport, and the other will be "target", which is the element that's being watched.
- observer: this is the observer object that's watching the elements. This is handy because when we want to perform an action only once when something comes into view, we can tell the observer to stop watching the element!
Here's an example:
[gist src=https://gist.github.com/benrgreene/a5fb2e46009c3c8f2e672037091b6ae4 file=callback.js][/gist]
That's it! Not actually all that much code. The other cool thing about it is that it has pretty good support amongst browsers. Naturally, Intersection Observers come in handy with things like lazy loading (see my previous post), but I've used them for a variety of different problems and features.