How to detect Enter key in JavaScript

Detecting the Enter key specifically is crucial for form submissions, search functionality, and creating intuitive user interfaces. As the creator of CoreUI with over 25 years of web development experience, I’ve implemented Enter key detection in countless form components and interactive elements. The most reliable and modern approach is checking for event.key === 'Enter' within a keydown event listener. This method works consistently across all browsers and provides clear, readable code.

Check for event.key === 'Enter' within a keydown event listener to detect Enter key presses.

document.addEventListener('keydown', function(event) {
    if (event.key === 'Enter') {
        console.log('Enter key was pressed!')
        // Your action here
    }
})

This code listens for all keydown events and specifically checks if the pressed key is ‘Enter’. When the Enter key is detected, you can execute your desired action, such as submitting a form or triggering a search. The event.key property returns the string ‘Enter’ for the Enter key, making the condition easy to read and understand.

Best Practice Note:

This is the exact pattern we use in CoreUI form components for enhanced user experience. Consider preventing the default behavior with event.preventDefault() if you’re handling the Enter key action yourself.


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.
CSS Selector for Parent Element
CSS Selector for Parent Element

How to check if an array is empty in JavaScript?
How to check if an array is empty in JavaScript?

How to Achieve Perfectly Rounded Corners in CSS
How to Achieve Perfectly Rounded Corners in CSS

How to Convert a Map to an Array in JavaScript
How to Convert a Map to an Array in JavaScript

Answers by CoreUI Core Team