How to detect key press in JavaScript
Detecting keyboard input is essential for creating interactive web applications, from form validation to keyboard shortcuts.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented keyboard event handling countless times in production components.
From my 25 years of experience in web development, the most reliable approach is using the keydown event with addEventListener.
This method provides consistent behavior across all modern browsers and gives you full control over the keyboard interaction.
Use addEventListener with the keydown event to detect when any key is pressed.
document.addEventListener('keydown', function(event) {
console.log(`Key pressed: ${event.key}`)
console.log(`Key code: ${event.keyCode}`)
})
This code adds an event listener to the entire document that triggers whenever a key is pressed down. The event.key property gives you the actual character or key name (like ‘Enter’, ‘Escape’), while event.keyCode provides the numeric code. The function fires immediately when the key is pressed, before it’s released.
Best Practice Note:
This is the same approach we use in CoreUI components for keyboard navigation and accessibility features. For better performance, consider adding the listener to specific elements rather than the document when possible.



