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 :
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();