onkeydown

The onkeydown event in HTML is triggered when a key is pressed, enabling developers to capture keyboard input for functions such as shortcuts or commands.

onkeydown event

The onkeydown event attribute is activated when a key is pressed on the keyboard. It can be utilized to run JavaScript based on particular key interactions.

The onkeypress event is outdated and may not function consistently across different browsers.
  • It does not detect certain keys like ALT, CTRL, SHIFT, and ESC in some environments.
  • For reliable key detection, use the onkeydown event, which supports all keys.

Syntax

In HTML

index.html
<element onkeydown="myScript">

In JS

script.js
object.onkeydown = function(){myScript};

In JavaScript, the addEventListener() function is used.

script.js
object.addEventListener("keydown", myScript);

Example

::event-onkeydown ::
index.html
<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The onkeydown Event</h2>
<p>Press a key in the input field:</p>
<input type="text" onkeydown="myFunction()">
<p id="demo"></p>
<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "You pressed a key inside the input field";
}
</script>

</body>
</html>

Value

This method does not consider the user's keyboard layout. For instance, pressing the key in the "Y" position on a QWERTY keyboard will always return "KeyY", regardless of whether the user has a QWERTY or Dvorak layout. To ensure the correct key is displayed based on the user's layout, you should use Keyboard.getLayoutMap().

Conclusion

The onkeydown event is a valuable tool for capturing keyboard <input> in HTML, allowing developers to implement interactive features such as shortcuts or key-based actions.