Last Updated: February 25, 2016
·
572
· smussell

Listen for keypress on non-form elements.

Here is a simple trick for listening to keypress and related events on elements other than text inputs. As long as you add a tabindex to the element, it can be selected and will accept keyboard events. Here's an example.

<div id='keyboardable' tabindex=1></div>    

Adding tabindex to the above allows you to focus on the div and start listening for keyboard input. Here is a live example:

http://jsfiddle.net/fmeHw/

You may be wondering, how is this useful? This (http://challenge.crownpartners.com) is a link to a weekend project I worked on a while back to help with some recruiting. When I did this I wasn't aware of this trick so I ended up using a hidden form element, had I known about this I could have used it as a cleaner alternative.

A more common use case is creating a button which you would like the user to be able to trigger via the keyboard.

P.S. Its always a good idea to consider mobile, this trick doesn't seem to work on iOS, haven't tested on Android or other mobile browsers.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside