Home > Software design >  javascript detect scrolling past the end of the window when scroll event doesn't fire
javascript detect scrolling past the end of the window when scroll event doesn't fire

Time:07-16

I have a site in which all sections take 100vh/vw, and I want to animate the opacity transition when user attempts to scroll up/down.

The thing is, the scroll event doesn't fire because the window hasn't really scrolled.

here's the codepen, and the gist of it:

// css
.section {
  width: 100vw;
  height: 100vh;
  opacity: 0;
  transition: opacity 0.5s;
}

.section.active {
  opacity: 1;
}

// html
<div className="section active">Some stuff here...</div>
<div className="section">Some stuff here...</div>

// js
window.addEventListener("scroll", () => {
  console.log("never fires")
})

is this even possible?

And if not, any ideas for a workaround?

CodePudding user response:

Should be <div >, not <div className="...">.

window.addEventListener("scroll", () => {
  console.log("now fires")
})
.section {
  width: 100vw;
  height: 100vh;
  opacity: 0;
  transition: opacity 0.5s;
}

.section.active {
  opacity: 1;
}
<div >Some stuff here...</div>
<div >Some stuff here...</div>

CodePudding user response:

Change keyword scroll to wheel, this event fires when you try to scroll from mouse/pad(using fingers)even there is not scroll

window.addEventListener("wheel", () => {
  console.log("event fires")
})

CodePudding user response:

You can listen for the wheel event and then if the user scrolls down, you can set the opacity of the next section to 1 and vice versa.

window.addEventListener('wheel', (e) => {
  let element = document.querySelector('.active');
  element.style.setProperty('opacity', 0);
  if ( e.deltaY > 0 ) {
    element.nextSibling.style.setProperty('opacity', 1);
  }
  else {
    element.previousSibling.style.setProperty('opacity', 1);  
  }
});
  • Related