Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to react to the Enter key and other keys

Short answer

The keydown event fires when a key is pressed. event.key holds its name:

<input id="message" placeholder="Type and press Enter">
<p id="out"></p>
<script>
  document.getElementById('message').addEventListener('keydown', (event) => {
    if (event.key === 'Enter') {
      document.getElementById('out').textContent = 'Sent: ' + event.target.value;
      event.target.value = '';
    }
  });
</script>

Keyboard shortcuts

The properties ctrlKey, shiftKey, altKey and metaKey tell which modifier keys are held:

document.addEventListener('keydown', (event) => {
  if ((event.ctrlKey || event.metaKey) && event.key === 's') {
    event.preventDefault();
    saveDocument();
  }
});

Enter in a textarea

In a chat, Enter usually sends the message, and Shift+Enter starts a new line:

textarea.addEventListener('keydown', (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault();
    sendMessage(textarea.value);
  }
});

Common mistake

The old properties keyCode and which are deprecated. Use event.key for characters and event.code for the physical key position.

// outdated
if (event.keyCode === 13) send();
 
// modern
if (event.key === 'Enter') send();

Thanks for reading!

Donate to the site — we work hard for you.