Track scroll depth 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++;
        }
    });
}());

This Snapshot can be added to a pageview event so that it triggers for all pages. It attaches a custom property percent to a new Scroll Depth event. When analyzing this event, you'll want to group the results by the percent property, which shows how far down the page a user scrolled, in increments of 25%

Note that the Snapshot property itself should not be used in analysis. It's essentially a shell that triggers the heap.track() call to create the custom event.