Skip to content

Commit

Permalink
Send scroll event to data layer #15098
Browse files Browse the repository at this point in the history
- Adds scroll listener
- Adds event to the dataLayer when thresholds are passed
- Removes listener after all thresholds are passed
  • Loading branch information
stephaniehobson committed Sep 18, 2024
1 parent c7961e8 commit 815a87b
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
53 changes: 53 additions & 0 deletions media/js/base/datalayer-trackscroll.es6.js
Original file line number Diff line number Diff line change
@@ -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);
3 changes: 2 additions & 1 deletion media/static-bundles.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down

0 comments on commit 815a87b

Please sign in to comment.