I'm trying to prevent the window from scrolling when the mouse wheel is used while over a canvas. I tried disabling it like this:
document.getElementById( "canvasId" ).onmousedown = function(event){
event.preventDefault();
};
And several other ways but nothing works see:
/
Make the browser window small so there is a scroll bar, then mouse wheel over the canvas and it will make the window scroll. How can I let the canvas receive the wheel message but prevent the window from scrolling?
I'm using jquery (not shown here).
I'm trying to prevent the window from scrolling when the mouse wheel is used while over a canvas. I tried disabling it like this:
document.getElementById( "canvasId" ).onmousedown = function(event){
event.preventDefault();
};
And several other ways but nothing works see:
http://jsfiddle.net/MZ9Xm/1/
Make the browser window small so there is a scroll bar, then mouse wheel over the canvas and it will make the window scroll. How can I let the canvas receive the wheel message but prevent the window from scrolling?
I'm using jquery (not shown here).
Share Improve this question asked Apr 23, 2015 at 18:39 PhilipPhilip 1,9114 gold badges26 silver badges42 bronze badges2 Answers
Reset to default 14You can use the wheel
event. You may need to use mousewheel
instead for other browsers than Firefox -- but please note that the mousewheel
event has since been deprecated in favor of WheelEvent
.
Vanilla JavaScript version
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>
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>
This worked quite well for me
document.addEventListener("mousewheel", (e)=>{
if(e.target === htmlCanvasRef) {
e.preventDefault()
canvasApp.zoom(/*do smth with e*/)
console.log('not scrolling')
} else {
console.log('scrolling')
}
}, { passive: false });