How to trigger the "Enter" key on keyboard with JS

Overview

Below are the steps to trigger a button when the user presses the "Enter" key:

  • Add an event listener for the keypress event listener and check if the user pressed the "Enter" key.
  • If the user presses the "Enter" key, use the click method of the button DOMElement. The click method will trigger the key click event.

Example

The below code demonstrates how to trigger a button click when the user presses the “Enter” key with JS.

Console
Trigger a button when user presses "enter" key

Explanation

  • Line 9: We create a button with the ID, btn. The click event will be triggered for this button when the user presses the "Enter" key.
  • Line 12: We get the button element and store it in a variable btn.
  • Lines 15–17: We add the click event lister for btn.
  • Lines 19–30: We add the keypress event to the document. When the keypress event occurs, the event object will contain the data of which key is pressed. The code of the pressed key will be present in keyCode or the which property of the event object. So, we check if the pressed keycode is equal to the Enter key code (13). If the "Enter" key is pressed, we'll call the click method of the btn DOMElement. The click method simulates a mouse click on the button.

Free Resources