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.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to Achieve Perfectly Rounded Corners in CSS
How to Achieve Perfectly Rounded Corners in CSS

How to round a number to two decimal places in JavaScript
How to round a number to two decimal places in JavaScript

How to Use Bootstrap Tooltip in Vue 3 – The Right Way with CoreUI
How to Use Bootstrap Tooltip in Vue 3 – The Right Way with CoreUI

How to sleep in Javascript
How to sleep in Javascript

Answers by CoreUI Core Team