Home >Web Front-end >JS Tutorial >How Can I Detect Up or Down Scroll Direction with jQuery?
When handling scroll events in jQuery, it can be useful to determine whether the scroll is moving up or down. This allows for different behaviors or content to be displayed based on the scroll direction.
To achieve this, you can leverage the scrollTop property of the window object and compare its current value to its previous value. Here's how to implement it:
var lastScrollTop = 0; $(window).scroll(function(event) { var st = $(this).scrollTop(); if (st > lastScrollTop) { // Downscroll code } else { // Upscroll code } lastScrollTop = st; });
In this code, lastScrollTop stores the previous scrollTop value. When the scroll event triggers, it retrieves the current scrollTop value and compares it to lastScrollTop. If the current value is greater than the previous value, the scroll is moving down (since scrollTop increases as you scroll down). Otherwise, the scroll is moving up.
The above is the detailed content of How Can I Detect Up or Down Scroll Direction with jQuery?. For more information, please follow other related articles on the PHP Chinese website!