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.
Name | Description |
---|---|
keydown | Triggered when the user presses a key. |
keypress | Triggered when a user presses and releases a key. |
keyup | Triggered when the user releases a key. |
KeyboardEvent has the following extra properties:
Name | Description | Returns |
---|---|---|
char | Returns the character represented by the key press. | string |
key | Returns the key that was pressed. | string |
ctrlKey | Returns true if the Ctrl key was down when the key was pressed. | boolean |
shiftKey | Returns true if the Shift key was down when the key was pressed. | boolean |
altKey | Returns true if the Alt key was down when the key was pressed. | boolean |
repeat | Returns 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>