-1

I tried to override Chrome's mouse wheel event with this code:

// Wheel handler
function wheel(event){
    var ret = true;

    if (event.wheelDelta) {
        // Tilt to the left
        if (event.wheelDeltaX > 0) {
            alert('Left');
            //window.history.back();
            ret = false;
        }
        // Tilt to the right
        if (event.wheelDeltaX < 0) {
            alert('Right');
            //window.history.forward();
            ret = false;
        }
    }

    event.returnValue = ret;
}

// Bind the onmousewheel event to our handler
window.onmousewheel = document.onmousewheel = wheel;

But it seems that when I tilt left/right, nothing happens. What's wrong with this userscript? Thanks.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Gregor Isack
  • 1,111
  • 12
  • 25

1 Answers1

0
  • Refer to the wheel event reference and use the proper event properties.
  • Also, don't use window.on...; always use addEventListener (or jQuery).
  • Use .preventDefault() and .stopImmediatePropagation() to block the default action.
  • Finally, depending on what you are trying to block, you may wish/need to bind to specific elements, rather than document.

Here's working code that shows the techniques. Run the snippet and try it:

var blockedNode = document.getElementById ("blockit");
blockedNode.addEventListener ("wheel", mouseTiltDetect);
//document.addEventListener ("wheel", mouseTiltDetect);

function mouseTiltDetect (zEvent) {
    var blockit = false;

    if (zEvent.deltaX) {
        if (zEvent.deltaX < 0) {        //--  Tilt to the left
            console.log ('Left');
            blockit = true;
        }
        else if (zEvent.deltaX > 0) {   //--  Tilt to the right
            console.log ('Right');
            blockit = true;
        }
    }

    if (blockit) {
        zEvent.preventDefault ();
        zEvent.stopImmediatePropagation ();
    }
}
pre {
    overflow-x: scroll;
    height: 5em;
    border: 1px solid gray;
}
<pre>
Horizontally scroll me using mouse wheel tilt. ... Chuck ipsum. Chuck Norris once tried to wear glasses. The result was him seeing around the world to the point where he was looking at the back of his own head.
</pre>
<hr>
<pre id="blockit">
But you can't scroll this the same way. ... Chuck ipsum. Although it is not common knowledge, there are actually three sides to the Force: the light side, the dark side, and Chuck Norris.
</pre>
Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295