From 815a87bd7b7394de4ae1fc80f959d5fa7e2d04d9 Mon Sep 17 00:00:00 2001 From: Stephanie Hobson Date: Wed, 18 Sep 2024 14:06:00 -0700 Subject: [PATCH] Send scroll event to data layer #15098 - Adds scroll listener - Adds event to the dataLayer when thresholds are passed - Removes listener after all thresholds are passed --- media/js/base/datalayer-trackscroll.es6.js | 53 ++++++++++++++++++++++ media/static-bundles.json | 3 +- 2 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 media/js/base/datalayer-trackscroll.es6.js diff --git a/media/js/base/datalayer-trackscroll.es6.js b/media/js/base/datalayer-trackscroll.es6.js new file mode 100644 index 00000000000..8aafb783305 --- /dev/null +++ b/media/js/base/datalayer-trackscroll.es6.js @@ -0,0 +1,53 @@ +/* + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ + +if (typeof window.dataLayer === 'undefined') { + window.dataLayer = []; +} + +const TrackScroll = {}; + +let thresholds = [25, 50, 75, 90]; + +TrackScroll.getDepth = () => { + const scrollHeight = document.documentElement.scrollHeight; + const innerHeight = window.innerHeight; + const scrollY = window.scrollY; + const scrollPosition = innerHeight + scrollY; + const depth = (100 * scrollPosition) / scrollHeight; + return depth; +}; + +TrackScroll.sendEvent = (threshold) => { + window.dataLayer.push({ + event: 'scroll', + percent_scrolled: String(threshold) + }); +}; + +TrackScroll.scrollListener = () => { + const currentDepth = TrackScroll.getDepth(); + + // get a list of thresholds we've passed + const matchingThresholds = thresholds.filter( + (threshold) => currentDepth >= threshold + ); + + // remove thresholds we've passed from list of ones we're looking for + thresholds = thresholds.filter((threshold) => currentDepth < threshold); + + // send the event for thresholds we passed + matchingThresholds.forEach((threshold) => { + TrackScroll.sendEvent(threshold); + }); + + // remove the event listener if we've scrolled past all thresholds + if (thresholds.length === 0) { + removeEventListener('scroll', TrackScroll.scrollListener); + } +}; + +window.addEventListener('scroll', TrackScroll.scrollListener); diff --git a/media/static-bundles.json b/media/static-bundles.json index e1456e334c0..0e9fba42690 100644 --- a/media/static-bundles.json +++ b/media/static-bundles.json @@ -1598,7 +1598,8 @@ "files": [ "js/base/experiment-amo.es6.js", "js/base/experiment-amo-init.es6.js", - "js/base/datalayer-productdownload-init.es6.js" + "js/base/datalayer-productdownload-init.es6.js", + "js/base/datalayer-trackscroll.es6.js" ], "name": "data" },