Home > Enterprise >  Execute event listener only once with scroll
Execute event listener only once with scroll

Time:05-02

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

CodePudding user response:

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;
});

  • Related