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 body
, 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 tabIndex
attribute:
-
Clicking on me will give me the focus!
-
Clicking on me will do nothing because I have no
tabIndex
.
The above focusable and non-focusable <div>
‘s are produced by this code:
<style type="text/css">
.focusable-test:focus {
box-shadow: 0 0 5px 1px #08F;
}
</style>
<ul>
<li><div class="focusable-test" tabindex="1234">Clicking on me will give me the focus!</div></li>
<li><div class="focusable-test">Clicking on me will do nothing because I have no <code>tabIndex</code>.</div></li>
</ul>
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! 😎
2 Comments
simplyencrypt · May 24, 2017 at 2:59 AM
Thanks For this Post I Really Enjoy Your text encryption | encrypt .
Quan · July 18, 2019 at 9:39 AM
Hi Chris, this was a useful trick, even over two years after your post. Thanks!