How do I capture a key press (or keydown) event on a div element?
To listen for keypresses on a div element, give the div a tabindex="0" and bind a keydown event listeners to it. Here's how it's done:
Following this, you will have to focus on the div (either programmatically or with a mouse click) then commence with your key pressing antics.
The tabindex Attribute
To make your div take part in keyboard navigation and be able to capture key events, you need to give it an attribute called tabindex="0":
However, don't leave your div wandering around invisibly. It's important for users to still detect where the focus is, so consider custom styling, or leaving the focus ring as it is for accessibility.
What jQuery has to say
For those who think in the jQuery language, you too can capture this elusive keypress event:
Just remember to grant our div the attention it needs with .focus(). However, in many cases, pure JavaScript might be more light-footed and sufficient.
Identifying the Captured Key
With the keydown event firmly under control, we use e.key or e.keyCode to discover which key was pressed. Do keep in mind that e.keyCode is flagged as deprecated, so stick with e.key:
If you're dealing with non-printable keys, prepare a keycodes table for reference. Just remember: with e.key, your code stays readable and your hair stays un-pulled.
Styling Our Focused Div
While we would use outline: none; to remove those pesky focus styles, let's remember our friends who rely on accessibility. Provide them with some eye-catching custom focus styles:
Listen Up, No jQuery Here!
Sometimes, you don't need jQuery. Plain old JavaScript can be just as effective and without the need for an external library:
Using custom event handling functions like the one above can give you more control and flexibility.
Astray Keys and Other Dangers
Keyboard events can be tricky. Watch out for browser inconsistencies and accessibility problems, and always test on different devices and assistive technologies.
The Pro Tip Checklist
- Programmatic Focus: Aim to focus the
divonly when it's relevant, like after user interaction. - Accessibility: Did you provide alternative focus styles? Good. We like to keep things user-friendly.
- Event Propagation: Get familiar with the event bubbling and capturing phases. They'll stop you from tearing your hair out later.
Was this article helpful?