Home >Web Front-end >JS Tutorial >How Can I Determine Scroll Direction in JavaScript Without Using jQuery?

How Can I Determine Scroll Direction in JavaScript Without Using jQuery?

DDD
DDDOriginal
2024-10-28 03:49:011100browse

How Can I Determine Scroll Direction in JavaScript Without Using jQuery?

Determining Scroll Direction without jQuery

Detecting Scroll Direction

Determining the direction of a scroll event can be achieved without relying on jQuery. Here's a JavaScript implementation:

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

// Adjust the element selector based on the target of your scroll event.
document.querySelector('body').addEventListener("scroll", function() {
   var st = window.pageYOffset || document.documentElement.scrollTop;
   if (st > lastScrollTop) {
      // Downscroll code
   } else if (st < lastScrollTop) {
      // Upscroll code
   }
   lastScrollTop = st <= 0 ? 0 : st; // Account for negative scrolling or devices with touch events
}, false);</code>

In this code:

  • lastScrollTop stores the previous scroll position.
  • The scroll event listener tracks the current scroll position in st.
  • By comparing st with lastScrollTop, you can determine the scroll direction.
  • The if statement executes when scrolling down, while the else if statement executes when scrolling up.
  • The lastScrollTop is updated to the current scroll position to prepare for the next scroll event.

Avoiding the "Back to Top" Button

Instead of adding a "Back to Top" button, you can incorporate a smoother approach by detecting scroll direction. For instance, you could:

  • Display a floating navigation bar that becomes visible when scrolling down and hides when scrolling up.
  • Use CSS animations to reveal or fade elements as the page is scrolled.
  • Adjust the opacity of elements on the page based on scroll direction, creating a parallax effect.

The above is the detailed content of How Can I Determine Scroll Direction in JavaScript Without Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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