33

Possible Duplicate:
Differentiate between scroll up/down in jquery?

Is it possible to detect if user scroll down or scroll up ?

Example :

$(window).scroll(function(){

    // IF USER SCROLL DOWN 
           DO ACTION

    // IF USER SCROLL UP 
           DO ANOTHER ACTION

});

Thanks

Community
  • 1
  • 1
Steffi
  • 6,287
  • 20
  • 68
  • 118

1 Answers1

48

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

Jordi van Duijn
  • 579
  • 1
  • 5
  • 3
  • This works very well! A simple ```e.preventDefault()``` will also not allow your scroll to go to any parent elements (like the page) if you're just wanting to do something on the scroll of a section and not actually scroll your element or its parents – Alex White Jul 24 '15 at 20:11
  • any ideas for this on apple trackpad or magic mouse with overflow hidden? http://stackoverflow.com/q/32512924/770127 – ryanve Sep 10 '15 at 23:36
  • 1
    This shouldn't be done anymore, browser sniffing hasn't been great practice for quite a while. There's another cross browser event now that'll be better to use. http://stackoverflow.com/a/33334461/3168107 – Shikkediel Oct 29 '15 at 11:38
  • This works really nice however doesn't work when I click my mouse wheel to scroll. – Tim Marshall Oct 12 '16 at 20:00
  • Thank you for the working snippet @Jordi van Duijn – Anahit DEV Apr 05 '17 at 16:07
  • change .bind to .on, .bind() is deprecated – decoder7283 Sep 22 '17 at 04:05