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

How Can You Determine Scroll Direction in JavaScript Without jQuery?

Susan Sarandon
Release: 2024-10-28 08:33:30
Original
613 people have browsed it

How Can You Determine Scroll Direction in JavaScript Without jQuery?

Detecting Scroll Direction Without jQuery

In web development, detecting the direction of a scroll can be useful for implementing functionality like infinite scrolling or collapsing toolbars. While libraries like jQuery offer straightforward solutions, let's explore how this can be achieved without their use.

To determine the scroll direction, we can track the previous scroll position (scrollTop or pageYOffset) and compare it with the current scroll position. This difference signifies whether we are scrolling up or down.

Here's a snippet of JavaScript that demonstrates this approach:

<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(){ 
   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

In this code, we check whether the current scroll position is greater than or less than the previous scroll position. If it's greater, we are scrolling down, and if it's less, we are scrolling up. Horizontal scrolling is also accounted for by checking if the scroll position is unchanged.

By storing the previous scroll position and comparing it with the current position, we can effectively detect the scroll direction without the need for external libraries. This method can be applied to various elements, including the window object for global scrolling detection.

The above is the detailed content of How Can You Determine Scroll Direction in 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!