25% off ProSNIPC25OFF

Add a "Scrolled" Class to Body on Scroll

Adds a "scrolled" CSS class to the <body> element once the page is scrolled past a configurable threshold, enabling CSS-driven sticky header or nav changes.

JavaScriptby SnipCraft
js
(function () {
    'use strict';

    var THRESHOLD = 80; // pixels from top before the class is applied

    function updateScrolledClass() {
        var scrolled = (window.scrollY || window.pageYOffset) >= THRESHOLD;
        document.body.classList.toggle('scrolled', scrolled);
    }

    window.addEventListener('scroll', updateScrolledClass, { passive: true });

    // Run once on page load in case the page is already scrolled (e.g. anchor links).
    updateScrolledClass();
})();
#css#frontend#javascript#navbar#scroll