Home > Web Front-end > JS Tutorial > body text

How can I detect scroll direction using JavaScript without jQuery?

Mary-Kate Olsen
Release: 2024-10-27 03:01:30
Original
623 people have browsed it

How can I detect scroll direction using JavaScript without jQuery?

Detecting Scroll Direction

Utilizing JavaScript's scroll event, it's possible to determine the direction of scrolling without the need for jQuery.

Detecting Scroll Direction

To accomplish this, we'll store the previous scrollTop value and compare it to the current scrollTop value.

<code class="javascript">var lastScrollTop = 0;

// element should be replaced with the actual target element on which you have applied scroll, use window in case of no target element.
element.addEventListener("scroll", function () { // or window.addEventListener("scroll"....
  var st = window.pageYOffset || document.documentElement.scrollTop; // Credits: "https://github.com/qeremy/so/blob/master/so.dom.js#L426"
  if (st > lastScrollTop) {
    // downscroll code
  } else if (st < lastScrollTop) {
    // upscroll code
  } // else was horizontal scroll
  lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
}, false);</code>
Copy after login

By employing this method, you can accurately detect the scrolling direction in any web page without relying on third-party libraries.

The above is the detailed content of How can I detect scroll direction using JavaScript without jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template