Sunrise in the fog

    Intersection Observers

    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:

    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= 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= 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:

    Here's an example:

    [gist src= 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.