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
DDDOriginal
2024-12-07 17:52:12705browse

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;
});

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!

Statement:
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