OMBD#12: Use window.IntersectionObserver To Track User Behavior
A tutorial on firing a callback function when an element enters the viewport
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.
⏮️ 🔛 ⏭️
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:
- Detect when the section enters the viewport.
- Fire a callback that will log that event on our analytics software e.g. Fathom, Matomo, Google Analytics.
- Disconnect the observer to avoid logging the event more than once.
Here’s a demo: