How can I determine the direction of a jQuery scroll event?
I'm looking for something to this effect:
$(window).scroll(function(event){
if (/* magic code*/ ){
// upscroll code
} else {
// downscroll code
}
});
Any ideas?
I'm looking for something to this effect:
$(window).scroll(function(event){
if (/* magic code*/ ){
// upscroll code
} else {
// downscroll code
}
});
Any ideas?
Check current vs previous scrollTop
scrollTop
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
// downscroll code
} else {
// upscroll code
}
lastScrollTop = st;
});
You can do it without having to keep track of the previous scroll top, as all the other examples require:
$(window).bind('mousewheel', function(event) {
if (event.originalEvent.wheelDelta >= 0) {
console.log('Scroll up');
}
else {
console.log('Scroll down');
}
});
I am not an expert on this so feel free to research it further, but it appears that when you use , the event being listened for is a 'scroll' event. $(element).scroll
But if you specifically listen for a event by using bind, the attribute of the event parameter to your callback contains different information. Part of that information is . If it's positive, you moved the mousewheel up. If it's negative, you moved the mousewheel down. mousewheel
originalEvent
wheelDelta
My guess is that events will fire when the mouse wheel turns, even if the page does not scroll; a case in which 'scroll' events probably are not fired. If you want, you can call at the bottom of your callback to prevent the page from scrolling, and so that you can use the mousewheel event for something other than a page scroll, like some type of zoom functionality.mousewheel
event.preventDefault()