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!