jquery mousewheel: detecting when the wheel stops?
I'm using Jquery mousewheel plugin and I would like like to be able to detect when the user has finished using the wheel. Similar functionality as the stop: event in the draggable stuff. Can somebody point me to the right direction?
There's no "stop" event here really - you get an event when you do scroll, so every time a mousewheel event happens the event is triggered...when there's nothing you'll get no events and your handler won't be firing.
You ca however detect when the user hasn't used it in say 250ms, like this:
$("#myElem").mousewheel(function() {
clearTimeout($.data(this, 'timer'));
$.data(this, 'timer', setTimeout(function() {
alert("Haven't scrolled in 250ms!");
//do something
}, 250));
});
You can give it a try here, all we're doing is storing the timeout on each use in using $.data()
, if you use it again before that time runs out, it gets cleared...if not then whatever code you wanted to run fires, the user has "finished" using their mousewheel for whatever period of time you're testing for.
To complete Nick Craver's answer:
var wheeldelta = {
x: 0,
y: 0
};
var wheeling;
$('#foo').on('mousewheel', function (e) {
if (!wheeling) {
console.log('start wheeling!');
}
clearTimeout(wheeling);
wheeling = setTimeout(function() {
console.log('stop wheeling!');
wheeling = undefined;
// reset wheeldelta
wheeldelta.x = 0;
wheeldelta.y = 0;
}, 250);
wheeldelta.x += e.deltaFactor * e.deltaX;
wheeldelta.y += e.deltaFactor * e.deltaY;
console.log(wheeldelta);
});
scrolling outputs:
start wheeling!
Object {x: -1, y: 0}
Object {x: -36, y: 12}
Object {x: -45, y: 12}
Object {x: -63, y: 12}
Object {x: -72, y: 12}
Object {x: -80, y: 12}
Object {x: -89, y: 12}
Object {x: -97, y: 12}
Object {x: -104, y: 12}
Object {x: -111, y: 12}
Object {x: -117, y: 12}
Object {x: -122, y: 12}
Object {x: -127, y: 12}
Object {x: -131, y: 12}
Object {x: -135, y: 12}
Object {x: -139, y: 12}
Object {x: -145, y: 12}
Object {x: -148, y: 12}
Object {x: -152, y: 12}
Object {x: -154, y: 12}
Object {x: -156, y: 12}
Object {x: -157, y: 12}
Object {x: -158, y: 12}
Object {x: -159, y: 12}
Object {x: -161, y: 12}
Object {x: -162, y: 12}
Object {x: -164, y: 12}
Object {x: -166, y: 12}
Object {x: -167, y: 12}
Object {x: -169, y: 12}
stop wheeling!
Here's how to do it in native JavaScript:
var _scrollTimeout = null;
function onMouseWheel() {
var d = ((typeof e.wheelDelta != "undefined") ? (-e.wheelDelta) : e.detail);
d = 100 * ((d>0)?1:-1);
console.log("Scroll delta", d);
clearTimeout(_scrollTimeout);
_scrollTimeout = setTimeout(function() {
console.log("Haven't scrolled in 250ms");
}, 250);
}
window.addEventListener( 'mousewheel', onMouseWheel, false );
window.addEventListener( 'DOMMouseScroll', onMouseWheel, false ); // firefox