How to detect Enter
document.addEventListener('keydown', (event) => {
if (event.key === "Enter" && !event.isComposing) {
// Enter was pressed
}
});
Use event.key to react to what the key means (it follows the keyboard layout) and event.code for its physical position, for example WASD in games. keyCode and which are deprecated: they still work, but their values differ between browsers and layouts.
How browsers treat Enter
Enter submits a form when focus is in a text input, and activates buttons and links. Check event.isComposing: while someone types in Chinese, Japanese or Korean, Enter confirms the composition and shouldn’t trigger your action. The numpad Enter has the same key but code NumpadEnter.
In React
<input onKeyDown={(e) => { if (e.key === "Enter") { /* … */ } }} />