Scroll Tracking via Snapshots

Capturing how far users scroll on your website is important to see if users are viewing all of the content on a page. The Snapshot below measures the full length of a page, and it captures a custom Scroll Depth event by triggering Heap’s client-side heap.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 Snapshot will not function as expected.

(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;
            heap.track('Scroll Depth', {
                percent: scrollPercent
            });
            quarters++;
        }
    });
}());