Question

I am trying to detect user scroll, if to left and to right then trigger and do something. But if user use trackpad scroll to top or to bottom then it will accidentally scroll to left or to right.

I think, may be not just check timer define per scroll also need to check if user scroll distance smaller than 20, we can differentiate that as accidentally and don't do anything.

I can't find the way check if user scroll distance, the element is not be scrollable so can't use scrollTop scrollLeft....

Any idea?

var scroll_timer;

$('img').bind('mousewheel', function(e) {
    if (e.originalEvent.wheelDeltaX < 0) {
        clearTimeout(scroll_timer);
        scroll_timer = setTimeout(function() {
            // .. do something
            // console.log('right');
        }, 200);
    } else if (e.originalEvent.wheelDeltaX > 0) {
        clearTimeout(scroll_timer);
        scroll_timer = setTimeout(function() {
            // .. do something
            // console.log('left');
        }, 200);
    }
});

Here is my JSFiddle

Was it helpful?

Solution

It looks like you can use e.originalEvent.wheelDeltaX to get scroll distance values. You could then use e.originalEvent.wheelDeltaY to see if the user is scrolling vertically more than horizontally and trigger stuff after that is true.

Here's a demo that works by testing if the value of scrolling Y is less that scrolling X and then allowing you to trigger if it's left or right after that. Seems to do the trick on my mac trackpad

var scroll_timer;

$('img').bind('mousewheel', function(e) {

    if((Math.abs(e.originalEvent.wheelDeltaX) > Math.abs(e.originalEvent.wheelDeltaY)))
    {
        if (e.originalEvent.wheelDeltaX < 0) {
            clearTimeout(scroll_timer);
            scroll_timer = setTimeout(function() {
                // .. do something
                console.log('right');
            }, 200);
        } else if (e.originalEvent.wheelDeltaX > 0) {
            clearTimeout(scroll_timer);
            scroll_timer = setTimeout(function() {
                // .. do something
                console.log('left');
            }, 200);
        }
    }
});

http://jsfiddle.net/andyface/5CfgT/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top