Prevent scrolling of window with canvas

I am trying to prevent the window from scrolling when the mouse wheel is being used during canvas. I tried to disable it like this:

document.getElementById( "canvasId" ).onmousedown = function(event){
    event.preventDefault();
};

      

And several other ways, but nothing works:

http://jsfiddle.net/MZ9Xm/1/

Make the browser window small, so there is a scroll bar, then the mouse wheel over the canvas, and this will make the window scroll. How can I let the canvas get the wheel message but prevent the window from scrolling?

I am using jquery (not shown here).

+3


source to share


1 answer


You can use event wheel

. You may have to use mousewheel

it for browsers other than Firefox instead - but note that the event has since been mousewheel

deprecated in favor of WheelEvent

.

Vanilla JavaScript

document.getElementById( "canvasId" ).onwheel = function(event){
    event.preventDefault();
};

document.getElementById( "canvasId" ).onmousewheel = function(event){
    event.preventDefault();
};
      

html, body {height:200%} canvas {border:4px solid red}
      

<canvas id="canvasId"></canvas>
      

Run codeHide result




JQuery version

$("#canvasId").bind("wheel mousewheel", function(e) {e.preventDefault()});
      

html, body {height:200%} canvas {border:4px solid red}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvasId"></canvas>
      

Run codeHide result


+8


source







All Articles