JavaScript Enter key event | Basic example code

Enter button pressed or not key detect by using an key event in JavaScirpt. Keycode (char code) 13 is the “Enter” key on the keyboard.

Example code Enter key event in JavaScript

HTML example code: Execute a function when the user releases a key on the keyboard and matches in if condition whether its enter key or not?

Using addEventListener with keyup

<!DOCTYPE html>
<html>
<body>

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

Output:

Or Use onkeypress property

<input id="enterDemo" type="text" onkeypress="return
enterKeyPressed(event)" />
<script>
   function enterKeyPressed(event) {
      if (event.keyCode == 13) {
         console.log("Enter key is pressed");
         return true;
      } else {
         return false;
      }
   }
</script>

Do comment if you have any doubts and suggestion on this JS event topic.

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.