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

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

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

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?

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.

Full-Stack Developer, Teacher, Maker, and general Things-Doer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store