Important Update 01/2015 - mousewheel event deprecated:
In the meantime the mousewheel
event is deprecated and replaced by wheel
.
MDN Docs for mousewheel say:
Do not use this wheel event.
This interface is non-standard and deprecated. It was used in non-Gecko browsers only. Instead use the standard wheel event.
Now you should use something like:
// This function checks if the specified event is supported by the browser.
// Source: http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
function isEventSupported(eventName) {
var el = document.createElement('div');
eventName = 'on' + eventName;
var isSupported = (eventName in el);
if (!isSupported) {
el.setAttribute(eventName, 'return;');
isSupported = typeof el[eventName] == 'function';
}
el = null;
return isSupported;
}
$(document).ready(function() {
// Check which wheel event is supported. Don't use both as it would fire each event
// in browsers where both events are supported.
var wheelEvent = isEventSupported('mousewheel') ? 'mousewheel' : 'wheel';
// Now bind the event to the desired element
$('#foo').on(wheelEvent, function(e) {
var oEvent = e.originalEvent,
delta = oEvent.deltaY || oEvent.wheelDelta;
// deltaY for wheel event
// wheelData for mousewheel event
if (delta > 0) {
// Scrolled up
} else {
// Scrolled down
}
});
});
P.S.
For the comment from Connell Watkins - "Could you explain the division by 120?",
there are some details on MSDN:
The onmousewheel event is the only event that exposes the wheelDelta property. This property indicates the distance that the wheel button has rotated, expressed in multiples of 120. A positive value indicates that the wheel button has rotated away from the user. A negative value indicates that the wheel button has rotated toward the user.
I left out the delta / 120
part in my method as there's no benefit IMO. Scrolling up is delta > 0
and down delta < 0
. Simple.