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 →

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Join the Conversation

7 Comments

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.