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%).

(function() {
    var quarters = 0;
    var scrollHeight, quarterHeight, scrollDistance, divisible, scrollPercent;
    document.addEventListener("scroll", function() {
        scrollHeight = document.documentElement.scrollHeight - window.innerHeight;
        quarterHeight = scrollHeight / 4;
        scrollDistance = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
        divisible = Math.trunc(scrollDistance / quarterHeight);
        if (quarters < divisible && divisible !== Infinity) {
            scrollPercent = divisible * 25;
            freshpaint.track('Scroll Depth', {
                percent: scrollPercent
            });
            quarters++;
        }
    });
}());

You can have an engineer install this script on your app, or you can use Freshpaint's Tag Manager to inject the script on your site. If you have any questions on how to achieve this, contact [email protected]

Last updated

Was this helpful?