Skip to content
Advertisement

Execute event listener only once with scroll

I have an event listener for an image that fades in on scroll down, and i want it to stop reappearing on scroll up.

Here is my code, would you be able to help me with that?

const checkpoint = 100;

window.addEventListener("scroll", () => {
  const currentScroll = window.pageYOffset;
  if (currentScroll <= checkpoint) {
    opacity = 1 - currentScroll / checkpoint;
  } else {
    opacity = 0;
  }
  document.querySelector(".front").style.opacity = opacity;
});

Thanks in advance

Advertisement

Answer

Based on your own condition of currentScroll <= checkpoint, this should stop the opacity from changing (i.e. stop the image from reappearing) once it has been set to 0

let checkpoint = 100;

window.addEventListener("scroll", () => {
  const currentScroll = window.pageYOffset;
  if (currentScroll <= checkpoint) {
    opacity = 1 - currentScroll / checkpoint;
  } else {
    opacity = 0;
    checkpoint = -1;
  }
  document.querySelector(".front").style.opacity = opacity;
});
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement