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! šŸ˜Ž

Categories: Blog

4 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!

Tony · August 30, 2022 at 9:27 AM

Tip: tabindex=”0″ means that the element should be focusable in sequential keyboard navigation, after any positive tabindex values and its order is defined by the document’s source order.

Docs: https://developer.mozilla.org/pt-BR/docs/Web/HTML/Global_attributes/tabindex

Susanna · January 17, 2023 at 5:39 PM

This should never be done, it’s terrible for accessibility. What will happen when you set a positive tabindex on elements which aren’t normally interactive is that they get added to the normal focus order of the page, which means that people navigating with the keyboard (such as those with mobility disabilities or blindness) end up having to tab through them as they navigate the page, which is extremely confusing and not at all desirable. The better way to handle this, depending on the situation, is either give the element a *negative* tabindex value and use JS to focus it when necessary, or change it to a natively focusable element.

Leave a Reply

Your email address will not be published. Required fields are marked *