Nick Nick - 7 months ago 31
Javascript Question

jquery - mouse scroll event fired in a strange way

I'm trying to call a function when the mouse scroll down and one when it scroll up, but unfortunately, it seams like they are both called.

http://codepen.io/nickimola/pen/ZWjOyB?editors=1010

In the pen, I'm using an horizontal scroller to change slide on mouse scroll down (simulates next) and on mouse scroll up (simulates prev).

If you open the console, you can see that the right message is printed, but strangely, it seams that when I scroll up, also the scroll down event is fired. It is a bit strange and difficult to explain, it is clearer from the pen above.

here's the code i'm using to detect scrolling:

$(document).ready(function(){
$('html').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta / 120 > 0) {
$.fn.fullpage.moveSlideLeft();
console.log('scrolling up !');
}
else{
$.fn.fullpage.moveSlideRight();
console.log('scrolling down !');
}
});
});


and this is the plugin i'm using for the horizontal slider and the callback function: https://github.com/alvarotrigo/fullPage.js#fullpagejs

JDB JDB
Answer

There are several possible answers to this question, depending on what you want your User Experience to be.

I can only test on a trackpad, but one possible solution is to require a greater input threshold before initiating a scroll action:

var delta = e.originalEvent.wheelDelta / 120;
if(delta >= 1) {
    $.fn.fullpage.moveSlideLeft();
    console.log('scrolling up !');
}
else if(delta <= -1){
    $.fn.fullpage.moveSlideRight();
    console.log('scrolling down !');
}

This will ignore small scroll actions, or tiny reverses in direction after the initial scroll.

But the real issue here is that you are attempting to call your moveSlideRight function on ever scroll event. The only reason that you're not having more issues is that moveSlideRight seems to ignore duplicate calls while it's still animating the page. It'd probably be better to use some sort of time tracking, so that an initial scroll in one direction will start the slide, and then ignore all other scroll actions for some period of time (perhaps half a second). Again, though, it depends on your desired UX.

Comments