Reputation:
var canvas = document.getElementById('myCanvas');
canvas.addEventListener('keydown', function (event) {
myHandleKeyboardEvent(event);
}, false);
This works fine for me. The events are sent to my handler.
But whenever I hit the space bar, the browser window scrolls.
Is there some way to swallow keyboard events before they get to the browser?
(I've tried putting the handler on the window
and the document
with the same results).
Upvotes: 0
Views: 384
Reputation: 542
Since it worked I am posting it as the answer:
var canvas = document.getElementById("myCanvas");
document.addEventListener(
"keydown",
function(event) {
if (document.activeElement && document.activeElement.id === canvas.id) {
event.preventDefault();
myHandleKeyboardEvent(event);
}
},
false
);
Snippet now includes important suggestion given by Kaiido This is a link to the working demo. https://codesandbox.io/s/o714xx10nz
Upvotes: 1