Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mousewheel event is not working in ie

Tags:

javascript

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!

like image 434
Juan Gonzales Avatar asked May 26 '13 04:05

Juan Gonzales


2 Answers

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.

like image 112
Dave Avatar answered Sep 28 '22 08:09

Dave


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

like image 39
Juan Gonzales Avatar answered Sep 28 '22 06:09

Juan Gonzales