Javascript DOM KeyboardEvent key Property

Introduction

Get the keyboard button that was pressed when a key event occurred:

var x = event.key;

Press a key on the keyboard in the input field.

View in separate window

<!DOCTYPE html>
<html>
<body>
<input type="text" size="40" onkeydown="myFunction(event)">
<p id="demo"></p>
<script>
function myFunction(event) {/*w  w  w .j  av  a2  s  .c  o  m*/
  var x = event.key;
  document.getElementById("demo").innerHTML = "The pressed key was: " + x;
}
</script>

</body>
</html>

The key property returns the identifier of the key that was pressed when a key event occurred.

Key identifiers are strings that identify keyboard buttons.

The return value of this property can be a string of:

  • A single character
  • A multi character, like "F1", "Enter", "HOME" or "CAPS LOCK"

This property is read-only.

The key property returns a String representing the pressed keyboard button.

  • Possible values:
  • A single character
  • A multi character, like "F1", "Enter", "HOME" or "CAPS LOCK"



PreviousNext

Related