How do I track scroll depth?
Capturing how far users scroll on your website is important to see if users are viewing all of the content on a page. The JavaScript example below measures the full length of a page, and then fires a custom Scroll Depth event by triggering Freshpaint’s client-side freshpaint.track() API every time a user scrolls a 25% of the full length (25%, 50%, 75%, 100%).
Scroll depth is calculated on the scroll location within the body element. If the content on your website is contained within a container element, then this event will not fire as expected.
1
(function() {
2
var quarters = 0;
3
var scrollHeight, quarterHeight, scrollDistance, divisible, scrollPercent;
4
document.addEventListener("scroll", function() {
5
scrollHeight = document.documentElement.scrollHeight - window.innerHeight;
6
quarterHeight = scrollHeight / 4;
7
scrollDistance = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
8
divisible = Math.trunc(scrollDistance / quarterHeight);
9
if (quarters < divisible && divisible !== Infinity) {
10
scrollPercent = divisible * 25;
11
freshpaint.track('Scroll Depth', {
12
percent: scrollPercent
13
});
14
quarters++;
15
}
16
});
17
}());
Copied!
Last modified 3mo ago
Copy link