Skip to content

JavaScript detect Enter key press | Example code

  • by

Use the EventTarget.addEventListener() method to listen for keyup/keydown event. And check the keyCode‘s value to see if an Enter key is pressed.

Enter key keycode is 13.

Example detect Enter keypress in JavaScript

HTML example code checks whether the Enter key is pressed or not.

<!DOCTYPE html>
<html>
<body>

  <script>
    document.addEventListener("keyup", function(event) {
    if (event.keyCode === 13) {
        alert(event.key + event.keyCode);
    }
});
  </script>
</body>
</html>

Output:

JavaScript detect Enter key press

Use the KeyboardEvent.key attribute similarly.

document.addEventListener("keyup", function(event) {
    if (event.key === 'Enter') {
        alert('Enter is pressed!');
    }
});

Do comment if you have any doubts or suggestions on this JS event code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading