Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add class if page is not at top

The following code is set to add a class on scroll. However, this presents an issue. If the user refreshes the page, the page will reload down the page where they left off and the class won’t be applied until the user schools. Is there a way to adjust the following to add the class if the scrollbar isn’t at the very top instead of apply on scroll?

let SCROLL_DISTANCE = window.scrollY;

const SELECTOR_HEADER = document.getElementById("header");
const CLASS_NAME_SCROLL = "scrolled";

window.addEventListener('scroll', function() { 
    SCROLL_DISTANCE = window.scrollY;

    if (SCROLL_DISTANCE >= 1) {
        SELECTOR_HEADER.classList.add(CLASS_NAME_SCROLL);
    } else {
        SELECTOR_HEADER.classList.remove(CLASS_NAME_SCROLL);
    }
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Save your check scroll logic in a function, and call it when the page loads:

const header = document.getElementById("header");

window.addEventListener("scroll", checkScroll);

function checkScroll() {
  header.classList.toggle("scrolled", window.scrollY >= 1);
}

checkScroll();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading