Published at
Updated at
Reading time
1min
This post is part of my Today I learned series in which I share all my web development learnings.

The IntersectionObserver API is a fairly new API that helps developers to figure out if an element is visibile or becomes visible. during scroll. It solves the problem of using costly operations like calling getBoundingClientRect inside of scroll handlers which can lead to janky scrolling.

Dan Callahan wrote an article on this topic and even when I spent a lot of time digging IntersectionObservers (I give a talk about it) he mentioned something that I missed so far.

Usually you initialize an IntersectionObserver like this:

// this fires when:
//   1. The target begins entering the viewport (0 < ratio < 1).
//   2. The target fully leaves the viewport (ratio <= 0).
let observer = new IntersectionObserver(handler, {
    threshold: 0
});

The snippet above defines a single threshold for the IntersectionObserver. But it is also possible to define several thresholds!!!

// this fires when:
//   1. The target begins entering the viewport (0 < ratio < 1).
//   2. The target fully enters the viewport (ratio >= 1).
//   3. The target begins leaving the viewport (1 > ratio > 0).
//   4. The target fully leaves the viewport (ratio <= 0).
let observer = new IntersectionObserver(handler, {
  threshold: [0, 1]
});

I have no idea how I could miss that!

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles