Using Intersection Observers

With the Intersection Observer coming to Firefox, a nice article covering it appeared on Mozilla Hacks.

The IntersectionObserver interface of the Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport.

To use it, create a new instance of IntersectionObserver, and then let it observe a given element (target):

let observer = new IntersectionObserver((entries, observer) => { /* … */});
observer.observe(target); // <-- Element to watch

Here's a demo pen:

See the Pen Hello IntersectionObserver by Dan Callahan (@callahad) on CodePen.

To not watch the target's relation to the viewport, but to another element, use the root option.

let observer = new IntersectionObserver((entries, observer) => { /* … */}, {
   root: parentElement,
observer.observe(target); // <-- Element to watch

Works in Edge 15, Chrome 51, and soon Firefox 55. For browsers that don't support it you can use a polyfill.

Intersection Observer comes to Firefox →
IntersectionObserver Polyfill →

Elsewhere , ,

Leave a Reply

Your email address will not be published. Required fields are marked *