How to check scroll depth using JavaScript

on in jQuery
Last modified on

This function checks after each scroll event to see if a visitor has achieved certain scroll depth milestones. In the case of this example, custom events will be fired off when a visitor scrolls 25%, 50%, 75%, and 100% of the way down the page.

/**
 * This function fires custom events at different scroll depth milestones.
 */

// Variables to prevent continuous firing of custom events

let scrollTwentyFive = true;
let scrollFifty = true;
let scrollSeventyFive = true;
let scrollOneHundred = true;

// Create the scrollPercentage

$(window).bind('scroll', function() {
    window.scrollPercent = ($(window).scrollTop() / ($(document).height() - $(window).height())) * 100;

    // Conditional code we'll use to fire events based on scrollPercentage.
    if (window.scrollPercent >= 25 && scrollTwentyFive) {
        // Do something for 25% scroll
        scrollTwentyFive = false;
    }
    if (window.scrollPercent >= 50 && scrollFifty) {
        // Do something for 50% scroll
        scrollFifty = false;
    }
    if (window.scrollPercent >= 75 && scrollSeventyFive) {
        // Do something for 75% scroll
        scrollSeventyFive = false;
    }
    if (window.scrollPercent >= 100 && scrollOneHundred) {
        // Do something for 100% scroll (bottom of page)
        scrollOneHundred = false;
    }
});