Example onkeydown event in JavaScript | Code

The onkeydown event is fired when user pressed a key (on the keyboard). You can Execute a JavaScript using onkeydown property.

HTML

<element onkeydown="myScript">

JavaScript

object.onkeydown = function(){myScript};

Code onkeydown event in JavaScript

HTML example code.

Get keypress value Use onkeydown property

Popup alert box with key value, when user press any value in input filed.

<!DOCTYPE html>
<html>
<body>

  <input onkeypress="alert(event.key)"/>

</body>
</html>

onkeydown event used object

<!DOCTYPE html>
<html>

<body>

  <input type="text" id="txtbox">

  <script>

    var input = document.getElementById('txtbox');

    input.keypress = function() {
      const key = event.key;
      alert(key);
      
    };
  </script>

</body>
</html>

onkeydown addEventListener()

<!DOCTYPE html>
<html>
<body>

  <input type="text" id="txtbox">

  <script>

    var input = document.getElementById('txtbox');
    
    input.addEventListener('keypress', function(event) {
      const key = event.key;
      alert(key);
    });
  </script>

</body>
</html>

Output:

Do comment if you have any doubts and 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

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