I am coding a page where the first time the user scrolls, it doesn't actually scroll the page down, instead it adds a class with a transition. I'd like to detect when the user is scrolling down, because if he scrolls up, I want it to do something else. All the methods that I've found are based on defining the current body ScrollTop, and then comparing with the body scrollTop after the page scrolls, defining the direction, but since the page doesn't actually scroll, the body scrollTop() doesn't change.
animationIsDone = false; function preventScroll(e) { e.preventDefault(); e.stopPropagation(); } $('body').on('mousewheel', function(e) { if (animationIsDone === false) { $("#main-header").removeClass("yellow-overlay").addClass("yellow-overlay-darker"); $(".site-info").first().addClass("is-description-visible"); preventScroll(e); setTimeout(function() { animationIsDone = true; }, 1000); } });
This is what I have come with, but that way it doesn't matter the direction I scroll it triggers the event
Windows assumes that the page is static and user needs to scroll the viewport(display), on the portion of page, user wants to see. If user wants to see lower part of the page, scroll down and vice-versa.
With natural scrolling, a trackpad or a mouse wheel no longer follows the direction of the scrollbars. Rather, the pointer responds as if your finger were touching the screen.
Fix Your Mouse's Jerky ScrollingChange the mouse battery. Change the mouse scroll settings. Swap the USB ports. Update the mouse's device driver.
The mousewheel
event is quickly becoming obsolete. You should use wheel
event instead.
This would also easily allow you to the vertical and/or horizontal scroll direction without scroll bars.
This event has support in all current major browsers and should remain the standard far into the future.
Here is a demo:
window.addEventListener('wheel', function(event) { if (event.deltaY < 0) { console.log('scrolling up'); document.getElementById('status').textContent= 'scrolling up'; } else if (event.deltaY > 0) { console.log('scrolling down'); document.getElementById('status').textContent= 'scrolling down'; } });
<div id="status"></div>
Try This using addEventListener
.
window.addEventListener('mousewheel', function(e){ wDelta = e.wheelDelta < 0 ? 'down' : 'up'; console.log(wDelta); });
Demo
Update:
As mentioned in one of the answers, the mousewheel event is depreciated. You should use the wheel event instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With