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?
Edit – This answer is a solution, but a much simpler and proper approach would be setting the
tabindexattribute 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.JSFIDDLE