Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one use Window.Onscroll method to include detection of scroll direction?

Tags:

javascript

Can one use Window.Onscroll method to include detection of scroll direction?

like image 685
David Okuniev Avatar asked Aug 03 '09 15:08

David Okuniev


People also ask

How does Onscroll work?

Definition and Usage. The onscroll event occurs when an element's scrollbar is being scrolled. Tip: use the CSS overflow style property to create a scrollbar for an element.

How can check scroll up and scroll down in react JS?

To detect when a user scrolls to bottom of div with React, we can check if the sum of the scrollTop and clientHeight properties of a scrollable element is equal to the scrollHeight property of the same element. We call the useRef hook to create a ref and we assign the returned ref to the inner div, which is scrollable.


2 Answers

If you record the scrollX and scrollY on page load and each time a scroll event occurs, then you can compare the previous values with the new values to know which direction you scrolled. Here's a proof of concept:

function scrollFunc(e) {
    if ( typeof scrollFunc.x == 'undefined' ) {
        scrollFunc.x=window.pageXOffset;
        scrollFunc.y=window.pageYOffset;
    }
    var diffX=scrollFunc.x-window.pageXOffset;
    var diffY=scrollFunc.y-window.pageYOffset;

    if( diffX<0 ) {
        // Scroll right
    } else if( diffX>0 ) {
        // Scroll left
    } else if( diffY<0 ) {
        // Scroll down
    } else if( diffY>0 ) {
        // Scroll up
    } else {
        // First scroll event
    }
    scrollFunc.x=window.pageXOffset;
    scrollFunc.y=window.pageYOffset;
}
window.onscroll=scrollFunc
like image 99
Edward Dale Avatar answered Sep 17 '22 14:09

Edward Dale


With jquery, you can also register a custom scroll event which supplies the scroll change as an argument to the event handler:

var previous_scroll = $(window).scrollTop();

$(window).on('scroll', function() {
    var scroll = $(window).scrollTop(),
        scroll_change = scroll - previous_scroll;
    previous_scroll = scroll;
    $(window).trigger('custom_scroll', [scroll_change]);
});

Then instead of scroll, bind to custom_scroll:

$(window).on('custom_scroll', function pos(e, scroll_change) {
    console.log(scroll_change);
});
like image 23
Greg Avatar answered Sep 18 '22 14:09

Greg