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
clickmethod of the buttonDOMElement. Theclickmethod 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.
Explanation
- Line 9: We create a button with the ID,
btn. Theclickevent 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
clickevent lister forbtn. - Lines 19–30: We add the
keypressevent to the document. When thekeypressevent occurs, the event object will contain the data of which key is pressed. The code of the pressed key will be present inkeyCodeor thewhichproperty 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 theclickmethod of thebtnDOMElement. Theclickmethod simulates a mouse click on the button.