How to determine the direction of scroll on the page?

05.04.20

Using jQuery, you can do this:

let lastScrollTop = 0;

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

    let top = $(this).scrollTop();
    if (lastScrollTop > top) {
        console.log('top');
    } else if (lastScrollTop < top) {
        console.log('down');
    }
    lastScrollTop = top;

});

Or the same thing can be written in native JavaScript

let lastScrollTop = 0;

window.addEventListener('scroll', function(){

    let top = window.pageYOffset;
    if (lastScrollTop > top) {
        console.log('top');

    } else if (lastScrollTop < top) {
        console.log('down');
    }
    lastScrollTop = top;

});
blog comments powered by Disqus