dzimi dzimi - 6 months ago 24
jQuery Question

Scrolling up triggers both up and down when scrolling up

I have a function which should console log

up
when scrolling up and
down
when scrolling down.

Scrolling down works fine, but when scrolling up the console logs both
up
and
down
.

Why isn't it just logging
up
when scrolling up, as it is just logging
down
when scrolling down?

function scrollTest() {

var lastScrollTop = 0;

$(window).scroll(function(event) {

var st = $(this).scrollTop();

if (st > lastScrollTop){
console.log('down');
} else if (st < lastScrollTop) {
console.log('up');
}

lastScrollTop = st;

});

};

$( window ).on( "scroll", function() {

scrollTest();

});

Answer

This fix it:

var lastScrollTop = 0;
function scrollTest() {


    $(window).scroll(function(event) {

        var st = $(this).scrollTop();

        if (st > lastScrollTop){
            console.log('down ' + st + " | " + lastScrollTop);
            lastScrollTop = st;
            return 0;
        } 
        if (st < lastScrollTop) {
            console.log('up ' + st + " | " + lastScrollTop);
            lastScrollTop = st;
            return 0;
        }
      });

    };

$( window ).on( "scroll", function() {

    scrollTest();

});

The problem is that var lastScrollTop = 0; was getting the value 0 on each scroll... here is the fiddle