0

Is it possible to have a jQuery or javascript listener for when a user tries to scroll, even if the web page is not scrollable? I need to execute some code when the user tries to scroll down, even if the web page is short enough that there is no scrolling.

Note this solution doenst need to work for touch-screens.

UPDATE I need different code to execute when the user tries to scroll up as opposed to down.

Evanss
  • 23,390
  • 94
  • 282
  • 505

3 Answers3

0

Update: used on instead of bind and inserted the direction of scrolling. Also added DOMMouseScroll in order for this to work in Firefox.

Just use:

$(window).on('mousewheel DOMMouseScroll',function(e){
    // To catch up or down scroll:
    e = e.originalEvent;
    // delta == 1 = down, delta == -1 = up;
    var delta = e.wheelDelta > 0 || e.detail < 0 ? 1 : -1;
}

Or bind it to something else if you prefer.

putvande
  • 15,068
  • 3
  • 34
  • 50
  • Sorry I wasnt detailed enough with my question, ive updated it now. I need to execute different code when a user tries to scroll up as opposed to down. – Evanss Aug 08 '13 at 11:03
  • As of jQuery 1.7, the `.on()` method is the preferred method for attaching event handlers to a document. – Fabio Poloni Aug 08 '13 at 11:03
  • You can put that code anywhere you want. As long as it is withing ` – putvande Aug 08 '13 at 11:32
0
$(window).on('mousewheel', function (e) {
    if (e.originalEvent.wheelDeltaY < 0) {
        alert("Scrolled down");
    } else if (e.originalEvent.wheelDeltaY > 0) {
        alert("Scrolled up");
    }
});

It seems like different browsers give you different deltas. This solution doesn't work in all browsers like IE!


I really suggest you to have a look at Brandon Aaron's Mousewheel-Plugin for jQuery, which works on IE, too: https://github.com/brandonaaron/jquery-mousewheel

With that plugin you should be able to get a better solution:

$(window).on('mousewheel', function(event, delta, deltaX, deltaY) {
    if (deltaY < 0) {
        alert("Scrolled down");
    } else if (deltaY > 0) {
        alert("Scrolled up");
    }
});
Fabio Poloni
  • 8,219
  • 5
  • 44
  • 74
0

Thanks for your answers and advice but ive found a version that works for me: Get mouse wheel events in jQuery?

$(document).ready(function(){
    $('body').bind('mousewheel', function(e){
        if(e.originalEvent.wheelDelta /120 > 0) {
            console.log('scrolling up !');
        }
        else{
            console.log('scrolling down !');
        }
    });
});
Community
  • 1
  • 1
Evanss
  • 23,390
  • 94
  • 282
  • 505