开发者

do something when scroll up and something else when scroll down in jquery

开发者 https://www.devze.com 2022-12-21 04:28 出处:网络
I want to add a little down arrow on my website when users scroll down and an arrow pointing up when they scroll up.

I want to add a little down arrow on my website when users scroll down and an arrow pointing up when they scroll up.

The only thing I managed开发者_开发百科 to do is this

$(document).ready(function(){
    $(window).scroll(function () {
        $("#bottomArrow").show(); 
        setTimeout(function(){ $("#bottomArrow").fadeOut() }, 2000);
    });
}); 

which does not recognize the up and down, just the "scroll".

How can I do this with jQuery?


You need to check which way $(document).scrollTop() has changed. You could do something like this:

$(function() {

    var prevScroll = $(document).scrollTop();

    $(window).scroll(function() {
        var newScroll = $(document).scrollTop();
        if(newScroll < prevScroll) {
            // Scrolled up
        } else {
            // Scrolled down
        }
        prevScroll = newScroll;
    });
});

Testcase here:

http://jsbin.com/arazu3/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号