I am trying to make a canvas app that responds to keyboard and mouse input. I have this code:
canvas = document.getElementById('canvas'); canvas.addEventListener('mousedown', function(event) { alert('mousedown'); }, false); canvas.addEventListener('keydown', function(event) { alert('keydown'); }, false);
The 'mousedown' alert comes up whenever I click the mouse, but the 'keydown' alert never comes up. The same code works fine on JS Bin: http://jsbin.com/uteha3/66/
Why isn't it working on my page? Does canvas not recognize keyboard input?
addEventListener keydown example This example logs the KeyboardEvent. code value whenever you press down a key inside the <input> element. <input placeholder="Click here, then press down a key."
The keydown() is an inbuilt method in jQuery which is used to trigger the keydown event whenever User presses a key on the keyboard. If the key is kept pressed, the event is sent every time the operating system repeats the key. So, Using keydown() method we can detect if any key is on its way down.
Set the tabindex of the canvas element to 1 or something like this
<canvas tabindex='1'></canvas>
It's an old trick to make any element focusable
Edit - This answer is a solution, but a much simpler and proper approach would be setting the tabindex
attribute on the canvas element (as suggested by hobberwickey).
You can't focus a canvas element. A simple work around this, would be to make your "own" focus.
var lastDownTarget, canvas; window.onload = function() { canvas = document.getElementById('canvas'); document.addEventListener('mousedown', function(event) { lastDownTarget = event.target; alert('mousedown'); }, false); document.addEventListener('keydown', function(event) { if(lastDownTarget == canvas) { alert('keydown'); } }, false); }
JSFIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With