Home  >  Article  >  Web Front-end  >  Here are a few title options, focusing on the \'how-to\' aspect of your article: * How to Detect Scroll Direction in JavaScript Without jQuery * JavaScript Scroll Direction Detection: A Sim

Here are a few title options, focusing on the \'how-to\' aspect of your article: * How to Detect Scroll Direction in JavaScript Without jQuery * JavaScript Scroll Direction Detection: A Sim

DDD
DDDOriginal
2024-10-27 09:10:30665browse

Here are a few title options, focusing on the

Detecting Scroll Direction without jQuery

When using JavaScript to execute a function on scroll, it can be beneficial to know the direction of the scroll. Without jQuery, this can be achieved by implementing a solution that stores and compares previous scrollTop values.

Solution

The following JavaScript code effectively detects scroll direction:

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

// Customize this to target the desired element for scroll detection.
document.addEventListener("scroll", function() {
  var st = window.pageYOffset || document.documentElement.scrollTop;
  if (st > lastScrollTop) {
    // Code to execute when scrolling down
  } else if (st < lastScrollTop) {
    // Code to execute when scrolling up
  }
  // Reset the lastScrollTop value to prevent false negatives on mobile devices.
  lastScrollTop = st <= 0 ? 0 : st;
}, false);</code>

This solution provides a way to detect scroll direction without the use of jQuery. By storing and comparing scrollTop values, it effectively identifies both downscrolling and upscrolling actions.

The above is the detailed content of Here are a few title options, focusing on the \'how-to\' aspect of your article: * How to Detect Scroll Direction in JavaScript Without jQuery * JavaScript Scroll Direction Detection: A Sim. 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