Search code examples
javascriptwebpackscrollevent-handlingdom-events

Why could window scroll event not being fired


I have this js class:

export class ScrollBehaviorComponent {
  init() {
    const body = document.querySelector('body')
    let previousScroll = window.pageYOffset || 0
    let scrollDirIsUp = false

    window.addEventListener('scroll', function(e) {
      const currentScroll = window.pageYOffset // never gets updated
      scrollDirIsUp = currentScroll > 0 && previousScroll >= currentScroll // never gets updated
      body.classList.toggle('body--scroll-up', scrollDirIsUp) // never gets updated

      alert('scroll is up: ', window.pageYOffset) // never happens
    })

    console.log(window) // I see this log, o_0
  }
}

export default ScrollBehaviorComponent

That I used already before but for this one specific project the event is not fired.

I load it like this:

import ScrollBehaviorComponent from 'Shared/scroll-behavior/scroll-behavior.component'

export const HomeModule = {
  init() {
    new ScrollBehaviorComponent().init()

    // rest of page's code..
  },
}

The problem is that even that the developer's console fires no error, the event is also never fired.

Not even if I input in the developers console (and again, no errors)

window.window.addEventListener('scroll', function(e) {
  console.log('scroll is up: ', window.pageYOffset) // never happens
})

Which is fired in stackoverflow as I'm typing.

enter image description here

What could it be the reason? somewhere in the app is stopping event propagation? If so, any clue how to find it? other guess? ( its an inherited project )


Solution

  • It could be that some element (the body itself or some nested div) has the css overflow property set to scroll.

    To try to identify which is you could add something like:

    document.querySelectorAll("*").forEach(
      element => element.addEventListener("scroll",
        ({target}) => console.log(target, target.id, target.parent, target.parent.id)
      )
    );
    

    just be sure to run it when the page is full rendered; then in your console you should have quite enough data to identify which element is scrolling.