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 <p>In this code:</p> <ul> <li>lastScrollTop stores the previous scroll position.</li> <li>The scroll event listener tracks the current scroll position in st.</li> <li>By comparing st with lastScrollTop, you can determine the scroll direction.</li> <li>The if statement executes when scrolling down, while the else if statement executes when scrolling up.</li> <li>The lastScrollTop is updated to the current scroll position to prepare for the next scroll event.</li> </ul> <h3>Avoiding the "Back to Top" Button</h3> <p>Instead of adding a "Back to Top" button, you can incorporate a smoother approach by detecting scroll direction. For instance, you could:</p> <ul> <li>Display a floating navigation bar that becomes visible when scrolling down and hides when scrolling up.</li> <li>Use CSS animations to reveal or fade elements as the page is scrolled.</li> <li>Adjust the opacity of elements on the page based on scroll direction, creating a parallax effect.</li> </ul></code>
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!