Keyboard Events

The keyboard events are triggered in response to key presses. The set of events in this category is shown in the following table.

NameDescription
keydownTriggered when the user presses a key.
keypressTriggered when a user presses and releases a key.
keyupTriggered when the user releases a key.

KeyboardEvent has the following extra properties:

NameDescriptionReturns
charReturns the character represented by the key press.string
keyReturns the key that was pressed.string
ctrlKeyReturns true if the Ctrl key was down when the key was pressed.boolean
shiftKeyReturns true if the Shift key was down when the key was pressed.boolean
altKeyReturns true if the Alt key was down when the key was pressed.boolean
repeatReturns true if the key is being held down.boolean
 
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
  <form>
    <p>
      <label for="fave">Survey: <input autofocus id="fave" name="fave" /></label>
    </p>
    <p>
      <label for="name">Name: <input id="name" name="name" /></label>
    </p>
    <button type="reset">Reset</button>
  </form>
  <span id="message"></span>
  <script type="text/javascript">
    var inputElems = document.getElementsByTagName("input");
    for ( var i = 0; i < inputElems.length; i++) {
      inputElems[i].onkeyup = handleKeyboardEvent;
    }
    function handleKeyboardEvent(e) {
      document.getElementById("message").innerHTML = "Key pressed: "
          + e.keyCode + " Char: " + String.fromCharCode(e.keyCode);
    }
  </script>
</body>
</html>
  
Click to view the demo
Home 
  JavaScript Book 
    DOM