\n\n\nFollowing this, you will have to focus on the div (either programmatically or with a mouse click) then commence with your key pressing antics.","image":"https://explain.codes/media/static/images/eightify-logo.svg","author":{"@type":"Person","name":"Nikita Barsukov","url":"https://explain.codes//author/nikita-barsukov"},"publisher":{"@type":"Organization","name":"Rational Expressions, Inc","logo":{"@type":"ImageObject","url":"https://explain.codes/landing/images/[email protected]"}},"datePublished":"2025-02-11T20:45:01.517Z","dateModified":"2025-02-11T20:45:03.622Z"}
Explain Codes LogoExplain Codes Logo

How do I capture a key press (or keydown) event on a div element?

javascript
keydown-event
event-handling
javascript-events
Nikita BarsukovbyNikita Barsukov·Feb 11, 2025
TLDR

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:

<div id="divKeyTrack" tabindex="0"></div> <script> var divToTrack = document.getElementById('divKeyTrack'); divToTrack.addEventListener('keydown', e => alert(`Key press alert: ${e.key}`)); divToTrack.focus(); // Don't forget this part, or your div will sulk and ignore keys </script>

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":

#divKeyTrack { outline: none; /* Stealth mode activated */ }

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:

$('#divKeyTrack').keydown(function(e) { console.log(`Key struck: ${e.key}`); });

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:

div.addEventListener('keydown', e => { console.log(`Pressed key: ${e.key}`); // 'Enter', 'Space', 'ArrowUp', etc. });

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:

#divKeyTrack:focus { border: 2px solid blue; /* Blue, because why not? */ }

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:

document.getElementById('divKeyTrack').addEventListener('keydown', function(e) { console.log(`Key: ${e.key}`); // Spits out the pressed key });

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

  1. Programmatic Focus: Aim to focus the div only when it's relevant, like after user interaction.
  2. Accessibility: Did you provide alternative focus styles? Good. We like to keep things user-friendly.
  3. Event Propagation: Get familiar with the event bubbling and capturing phases. They'll stop you from tearing your hair out later.