[TIP] addEventListener for enter key

How to use addEventListener for the enter key

Jul 6, 2023 | Read time 8 minutes

🔔 Table of contents

Introduction

To determine if the user is hitting the enter key, we can use addEventListener function on the “keydown” event and check for the event keyCode of 13 or key value of “Enter”:

event.keyCode === 13 || event.key === 'Enter'

A common requirement that comes up with my web projects to listen to when the user hits the enter key and run some code when that happens.

Now the HTML element we want to attach a listener to could be an input field, a textarea, or any other HTML element.

To do this we generally want to follow the steps:

  1. Get a reference to the element using Javascript
  2. Attach the addEventListener function to the referenced element in step 1. We should be listening to the keydown event.
  3. Check the event object for keyCode (13) or key values = “Enter”
  4. Perform the desired action when the Enter key is pressed. It could be submitting a form, triggering a search, or any other action specific to your application.

Here’s an example to do this (replace ‘myInput’ with the appropriate ID or selector for your input element):

// 1. Get a reference to the input element
const inputElement = document.getElementById('myInput');

// 2. Attach the addEventListener
inputElement.addEventListener('keydown', function(event) {
  // 3. Check the event object
  if (event.keyCode === 13 || event.key === 'Enter') {
    console.log('Enter key was pressed');
    // 4. Perform the desired action. 
    // Add your code here to handle the Enter key press event
  }
});

Events thats fired when the user hits enter:

Why do we need to listen to the keydown event type instead of other events?

Every time when the user hits enter, the keydown is triggered first!

For a given key press, the sequence of KeyboardEvents fired is as follows assuming that Event.preventDefault is not called:

  • A keydown event is first fired. If the key is held down further and the key produces a character key, then the event continues to be emitted in a platform implementation dependent interval and the KeyboardEvent.repeat read only property is set to true.
  • If the key produces a character key that would result in a character being inserted into possibly an <input>, <textarea> or an element with HTMLElement.contentEditable set to true, the beforeinput and input event types are fired in that order. Note that some other implementations may fire keypress event if supported. The events will be fired repeatedly while the key is held down.
  • A keyup event is fired once the key is released. This completes the process.

In sequence 1 & 3, the KeyboardEvent.key attribute is defined and is set appropriately to a value according to the rules defined earlier.

event.keyCode vs event.key?

Now in the example above, you may have noticed that I am using both the event.keyCode and event.key properties.

They both are similar - the only difference is browser support.

event.keyCode

This property provides the numerical code of the key that was pressed during the event.

It is an older property and has been deprecated in favor of event.key. However, it is still supported by most browsers for backward compatibility.

event.key

This property represents the string value that corresponds to the key that was pressed during the event.

It provides a more human-readable and standardized way of identifying keys. For example, it returns “Enter” for the Enter key, “ArrowUp” for the Up arrow key, and so on.

It is recommended to use event.key instead of event.keyCode for better consistency and future compatibility.

We need to keep in mind on browser compatibility. With older browsers (eg IE) the event.key property is not supported. In this case, you have to fall back to using event.keyCode.

How to detect enter key in React

If you are in a React project, using addEventListener should be similar. One thing to keep mind is the “target” element.

As an example, we can target the “document” DOM element in a React component:

import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    const handleKeyPress = (event) => {
      if (event.key === 'Enter' || event.keyCode === 13) {
        // Perform your desired action here
        console.log('Enter key pressed');
      }
    };

    document.addEventListener('keydown', handleKeyPress);

    return () => {
      document.removeEventListener('keydown', handleKeyPress);
    };
  }, []); // Empty dependency array to run the effect only once

  return <div>My Component</div>;
}

export default MyComponent;

In the example above, we use the useEffect hook to add and remove the event listener.

The event listener is attached to the keydown event on the document object. When the Enter key is pressed (event.key === ‘Enter’), the desired action is performed (in this case, logging a message to the console).

The cleanup function returned by useEffect is used to remove the event listener when the component unmounts - this way we can avoid memory leaks.

You can place this code within your React component to add the event listener for the Enter key.

You will need to fill out the the handler with your own code.

Submit form on enter key press

Generally, if you have a HTML form, you will not need to add listeners for the Enter key.

By default, HTML forms are designed to submit when the user presses the Enter key (as long as there is a submit button within the form or an input element with the type=“submit” attribute)

As an example, the HTML form below will be submitted when the user hits Enter key:

<!DOCTYPE html>
<html>
<head>
  <title>Submit Form on Enter Key Press</title>
</head>
<body>
  <form>
    <input type="text" id="myInput" />
    <input type="submit" value="Submit" />
  </form>
</body>
</html>

Now this is just a basic form submit. If you need additional customization or want to perform specific actions when the Enter key is pressed, such as validation or AJAX requests, JavaScript can be used to enhance the functionality.

But for basic form submission on Enter key press, HTML alone should suffice.

Summary

In this post we went over how to listen to the Enter key press. We can do this with the addEventListener function and listening on the “keydown” event type.

We then can check the event object for the values “keyCode” or “key”.

When the user hits the enter key, “keyCode” should be 13 and “key” should be “Enter”.

We need to check both to maximize browser support. “keyCode” is deprecated and the preferred way to do it is with the “key” property.

This allows a more easy way to read which key is pressed and allows for internationalization scenarios!

👋 About the Author

G'day! I am Huy a software engineer based in Australia. I have been creating design-centered software for the last 10 years both professionally and as a passion.

My aim to share what I have learnt with you! (and to help me remember 😅)

Follow along on Twitter , GitHub and YouTube