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.
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:
- 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:
If you liked this story, you may also like:
1 Minute To Become A Better Developer (#11)
Learn how to use Regex’s Negative Lookahead, in one minute.
1 Minute To Become A Better Developer (#13)
Learn how to count the total number of lines in a Git repository, in one minute.