-
Notifications
You must be signed in to change notification settings - Fork 913
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
- Loading branch information
1 parent
c7961e8
commit 815a87b
Showing
2 changed files
with
55 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters