2

How can I detect the scroll direction (mousewheel up/down) without scrolling the page? My page wrapper has a height of 100%, so there is no content to scroll, but I need the scroll direction from the mousewheel.

Since Google Maps does the same (using the mousehweel for zoom without "scrolling" the page), I wonder how to achieve this.

Slevin
  • 4,268
  • 12
  • 40
  • 90
  • Here are informations about how to do what you want : http://www.adomas.org/javascript-mouse-wheel/ – Martin Jan 06 '14 at 11:28

4 Answers4

8

If you are talking about the mouse wheel, you can use addEventListener on the window. event.wheelDelta will have a delta of -120 or 120, for scrolling down and up, respectively.:

window.addEventListener('mousewheel', function(e){
    wDelta = e.wheelDelta < 0 ? 'down' : 'up';
    console.log(wDelta);
});

JSFiddle

Of course, you'll need to cater for different browsers. But i'll leave that up to you. See here

Community
  • 1
  • 1
George
  • 36,413
  • 9
  • 66
  • 103
1

You can add handler to mousewheel event with getting not only event object, but also wheel delta.

// Using jQuery library
$(function() {
    $('body').bind('mousewheel', function(event, delta) {
       // delta > 0 scroll up 
       // delta < 0 scroll down
    });
});

Pure javascript:

document.onmousewheel = function(evt){
    console.log(evt) // take a look in your console at evt.wheelDeltaX, evt.wheelDeltaY
     //evt.wheelDeltaX is horizont scroll
     //evt.wheelDeltaY is vertical scroll
     //evt.wheelDelta is deltas x+y 

     // if evt.wheelDeltaY < 0 then scroll down, if >0 then scroll up
     // if evt.wheelDeltaX < 0 then scroll left, if >0 then scroll right
}
Epsil0neR
  • 1,676
  • 16
  • 24
0

check out jQuery MouseMove http://api.jquery.com/mousemove/ store the previous x y into variables and compare it with the current onces to determine the direction of the mouse pointer

osmancode
  • 291
  • 2
  • 6
0

I modified Georges answer to work with modern browsers. The mousewheel event is obsolete and thus doesn't work anymore.

The following code snippet should work in all modern browsers:

window.addEventListener('wheel', function(e){
    let wDelta = e.deltaY > 0 ? 'down' : 'up';
    console.log(wDelta);
});
NoNickAvailable
  • 398
  • 1
  • 2
  • 12