The HTML DOM KeyboardEvent Object represents an event when user presses a key on keyboard.
Properties
Here, “KeyboardEvent” can have the following properties and methods −
Property/Method | Description |
---|---|
altKey | It returns whether the "ALT" key was pressed or not |
charCode | It returns the Unicode character code of the key |
code | It returns the code of the key |
ctrlKey | It returns whether the "CTRL" key was pressed or not |
getModifierState() | It returns true if the specified key is activated and false if inactive |
isComposing | It returns whether the state of the event is composing or not |
key | It returns the key value of the key represented by the event |
keyCode | It returns the Unicode character code of the key that triggered the event |
location | It returns the location of a key on the keyboard or device |
metaKey | It returns whether the "meta" key was pressed when the key event was triggered |
repeat | It returns whether a key is being hold down repeatedly, or not |
shiftKey | It returns whether the "SHIFT" key was pressed when the key event was triggered |
which | It returns the Unicode character code of the key that triggered the event |
Events
And, following are the events that act on keyboardEvent Object −
Event | Description |
---|---|
onkeydown | The event occurs when the user is pressing a key |
onkeypress | The event occurs when the user presses a key |
onkeyup | The event occurs when the user releases a key |
Example
Let us see an example for key property −
<!DOCTYPE html> <html> <head> <title>KeyboardEvent key</title> <style> form { width:70%; margin: 0 auto; text-align: center; } * { padding: 2px; margin:5px; } input[type="button"] { border-radius: 10px; } </style> </head> <body> <form> <fieldset> <legend>KeyboardEvent-key</legend> <label>Fill in the blanks: <input type="text" id="textSelect" placeholder="__ for Ball" onkeypress="getEventData(event)" autocomplete="off"> </label> <div id="divDisplay"></div> </fieldset> </form> <script> var divDisplay = document.getElementById("divDisplay"); var textSelect = document.getElementById("textSelect"); function getEventData(InputEvent) { if(InputEvent.key === 'B') divDisplay.textContent = 'Correct Answer'; else if(InputEvent.key === 'b') divDisplay.textContent = 'Close call, you might have caps lock turned off'; else divDisplay.textContent = 'Try Again, '+textSelect.placeholder; textSelect.textContent = ''; } </script> </body> </html>
Output
This will produce the following output −
Before typing anything in the text field −
After typing ‘b’ in the text field −
After typing ‘B’ in the text field −