Home > Web Front-end > JS Tutorial > How Can I Detect Up or Down Scroll Direction with jQuery?

How Can I Detect Up or Down Scroll Direction with jQuery?

DDD
Release: 2024-12-07 17:52:12
Original
731 people have browsed it

How Can I Detect Up or Down Scroll Direction with jQuery?

Detecting the Direction of jQuery Scroll Events

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;
});
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template