Recently I have been working on making a simple snake game and wanted to know what my options were for capturing keyboard events other than simply adding event listeners to the
document, or the
window. Amongst the obvious reasons for avoiding adding event listeners globally, I just want to make a prototype that will create one
canvas element which will capture keyboard events. After doing a quick Google search I found this awesome article saying that it is possible to make any element focusable.
For example make an element as innocuous as a
<div> element focusable by simply defining it’s
Clicking on me will give me the focus!
Clicking on me will do nothing because I have no
The above focusable and non-focusable
<div>‘s are produced by this code:
- Clicking on me will give me the focus!
- Clicking on me will do nothing because I have no
As you can see, only the
<div> with a set
tabIndex is truly focusable. I plan on using this cool hack to make my game’s canvas focusable. I hope you find this neat trick useful as well! 😎