I am working on an application and I need to track the mouse wheel movement but my functions are not working as I expect in Internet Explorer. It works in all other browsers but not IE, any ideas on what I am doing wrong?
JS...
var request = true;
var onMouseWheelSpin = function(event) {
if(request === true){
request = false;
var nDelta = 0;
if (!event) { event = window.event; }
// cross-bowser handling of eventdata to boil-down delta (+1 or -1)
if ( event.wheelDelta ) { // IE and Opera
nDelta= event.wheelDelta;
if ( window.opera ) { // Opera has the values reversed
nDelta= -nDelta;
}
}
else if (event.detail) { // Mozilla FireFox
nDelta= -event.detail;
}
if (nDelta > 0) {
zoomFun( 1, event );
}
if (nDelta < 0) {
zoomFun( -1, event );
}
if ( event.preventDefault ) { // Mozilla FireFox
event.preventDefault();
}
event.returnValue = false; // cancel default action
}
}
var zoomFun = function(delta,e) {
if(delta > 0){ // zoom in
alert("In");
}else{ // zoom out
alert("Out");
}
request = true;
}
var setupMouseWheel = function(){
// for mouse scrolling in Firefox
var elem = document.getElementById("zoom");
if (elem.addEventListener) { // all browsers except IE before version 9
// Internet Explorer, Opera, Google Chrome and Safari
elem.addEventListener ("mousewheel", onMouseWheelSpin, false);
// Firefox
elem.addEventListener ("DOMMouseScroll", onMouseWheelSpin, false);
}else{
if (elem.attachEvent) { // IE before version 9
elem.attachEvent ("onmousewheel", onMouseWheelSpin);
}
}
}
I am calling the setupMouseWheel function onload in the body aka
<body onload="setupMouseWheel();">
Thanks for the help!
To listen to the mouse wheel, it's best to listen to DOMMouseScroll, mousewheel and wheel. The last one is IE, and is the only one you're not listening for.
I'll also point out that jQuery has a shortcut for binding multiple events:
$(elem).on("DOMMouseScroll mousewheel wheel", onMouseWheelSpin);
update: noticed that though you tagged this as jQuery, you're not actually using it. To do this without jQuery, just carry on as you are but add a wheel event listener like the others.
I finally found a great cross browser approach here for anyone who has a similar issue
https://developer.mozilla.org/en-US/docs/Web/Reference/Events/wheel
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With