0

I have a div that has an onScroll handler and I need to know the direction where the user will scroll(to top or bottom).

My html:

<body>
 <div>
  Section1
 </div>
 <div>
  Section1
 </div>
</body>

My js:

document.addEventListener('scroll', (event) => {
        if(....){
          console.log(user scroll to top); 
        }else {
          console.log(user scroll to bottom);
        }
    });

What I should write instead ...

VanyaIvan
  • 3
  • 7

2 Answers2

1

You can use window.scrollY to determinate in which position scroll is. Of course when value of this is 0 is mean that is the on the top. It can be a little bit tricky how to get max window scroll height, but below is the way.

     if (window.scrollY === 0) {
        console.log("user scroll to top");
      } else if (window.scrollY + 1 >= document.documentElement.offsetHeight - window.innerHeight ) {
        console.log("user scroll to bottom");
      }
Kishieel
  • 1,811
  • 2
  • 10
  • 19
0

Elements have this property: scrollTop which is the distance in pixels to the top,

let previousTop = 0;

document.onscroll = (event) => {
  if(previousTop < event.target.scrollTop){
    console.log(user scroll to bottom); 
  }else {
    console.log(user scroll to top);
  }
  previousTop = event.target.scrollTop;
});