Maximilien Ollier
Maximilien Ollier

Reputation: 37

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

Upvotes: 1

Views: 725

Answers (2)

Rahul Dhiman
Rahul Dhiman

Reputation: 29

window.addEventListener("scroll", function(e) {
      
},{once:true});

Upvotes: 0

Aneesh
Aneesh

Reputation: 1715

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

Upvotes: 2

Related Questions