Home >Web Front-end >JS Tutorial >How Can I Determine Scroll Direction in JavaScript Without Using jQuery?
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:
Instead of adding a "Back to Top" button, you can incorporate a smoother approach by detecting scroll direction. For instance, you could:
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!