Reputation: 4222
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.
Upvotes: 2
Views: 2357
Reputation: 398
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);
});
Upvotes: 0
Reputation: 1704
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
}
Upvotes: 1
Reputation: 291
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
Upvotes: 0
Reputation: 36784
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);
});
Of course, you'll need to cater for different browsers. But i'll leave that up to you. See here
Upvotes: 8