I've got an image in a fixed-position div. The following code is fading the image in where I want to, but initially the image is visible. Once I start scrolling, it disappears and then reappears when it should. Trying to figure out why the image is displaying on page load.
const checkpoint = 500;
window.addEventListener("scroll", () => {
const currentScroll = window.pageYOffset;
if (currentScroll <= checkpoint) {
opacity = 0 - currentScroll / checkpoint;
} else {
opacity = 1;
}
document.querySelector(".sticky-logo-fade-in").style.opacity = opacity;
});
You can store the callback in a variable, then call it on page load:
const checkpoint = 500;
const scrollHandler = () => {
const currentScroll = window.pageYOffset;
if (currentScroll <= checkpoint) {
opacity = 0 - currentScroll / checkpoint;
} else {
opacity = 1;
}
document.querySelector(".sticky-logo-fade-in").style.opacity = opacity;
}
window.addEventListener("scroll", scrollHandler);
scrollHandler();