OMBD#12: Use window.IntersectionObserver To Track User Behavior

A tutorial on firing a callback function when an element enters the viewport

Jon Portella
1 min readMar 10, 2021

Welcome to issue #12 of One Minute Better Developer, where you become a more successful software developer by reading short nuggets of knowledge, one minute at a time.

⏮️ 🔛 ⏭️

Art by my buddy Loor Nicolas

The problem

Our website has a new and shiny landing page. We are getting lots of visits, so the marketing team has asked us to track how many of those visitors scroll down to the Call To Action section.

How can we do that?

A solution

Use window.IntersectionObserver to:

  1. Detect when the section enters the viewport.
  2. Fire a callback that will log that event on our analytics software e.g. Fathom, Matomo, Google Analytics.
  3. Disconnect the observer to avoid logging the event more than once.

Here’s a demo:

Demonstration of window.IntersectionObserver to log user scroll to a certain section.

--

--

Jon Portella

Software Engineer @ Pinterest - Teacher, maker, and general things do-er. - https://www.linkedin.com/in/jonportella/ - Toronto, Canada