Categories
JavaScript Answers

How to detect scroll direction with JavaScript?

Spread the love

Sometimes, we want to detect scroll direction with JavaScript.

In this article, we’ll look at how to detect scroll direction with JavaScript.

How to detect scroll direction with JavaScript?

To detect scroll direction with JavaScript, we can listen to the scroll event.

For instance, we write

let lastScrollTop = 0;

element.addEventListener(
  "scroll",
  () => {
    const st = window.pageYOffset || document.documentElement.scrollTop;
    if (st > lastScrollTop) {
      console.log("scrolling down");
    } else {
      console.log("scrolling up");
    }
    lastScrollTop = st <= 0 ? 0 : st;
  },
  false
);

to call addEventListener to listen to the 'scroll' event on window.

And then we get the current scroll position with

window.pageYOffset || document.documentElement.scrollTop

We then compare st with lastScrollTop to get the scroll position.

If st is bigger than lastScrollTop then we’re scrolling down.

After the if statement, we set lastScrollTop to the current scroll position which will change when we scroll again.

Conclusion

To detect scroll direction with JavaScript, we can listen to the scroll event.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *