Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect user scroll down or scroll up in jQuery [duplicate]

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

like image 343
Steffi Avatar asked Mar 31 '12 16:03

Steffi


1 Answers

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.

like image 54
Jordi van Duijn Avatar answered Oct 31 '22 08:10

Jordi van Duijn