Javascript Get Scroll/Wheel Direction
document window has a “wheel” event. Nothing beats the practice of exploring the browser console to see what information is readily available.
console logging the wheel event returns a lot of useful info, including direction via deltaY. This number either increases positively or decreases negatively.
The code:
Add event listener (do something special for Internet Explorer because it’s special)
if(window.addEventListener){ addEventListener('wheel', whichDirection, false); } else if (window.attachEvent) { // ie attachEvent('wheel', whichDirection, false); }
Create function (naming the parameter ‘event’ is good practice offering clarity)
function whichDirection(event){ console.log(event + ' WheelEvent has all kinds of good stuff to work with'); var scrollDirection = event.deltaY; if(scrollDirection === 1){ console.log('meet me at the club, going down’, scrollDirection); } else if(scrollDirection === -1) { console.log('Going up, on a tuesday’, scrollDirection); } }
Using jQuery (the function remains the same)
$(window).on('wheel', function(){ whichDirection(event); });
Throttle / Debounce:
Watch this in the console, you’ll see the WheelEvent firing over and over. Check out David Walsh’s article on creating a Debounce Function. You’ll be up and running with some hotness in short order.
Response Given to Stack Overflow Question here












