HTML DOM KeyboardEvent Object

HTMLWeb DevelopmentFront End Technology

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/MethodDescription
altKeyIt returns whether the "ALT" key was pressed or not
charCodeIt returns the Unicode character code of the key
codeIt returns the code of the key
ctrlKeyIt returns whether the "CTRL" key was pressed or not
getModifierState()It returns true if the specified key is activated and false if inactive
isComposingIt returns whether the state of the event is composing or not
keyIt returns the key value of the key represented by the event
keyCodeIt returns the Unicode character code of the key that triggered the event
locationIt returns the location of a key on the keyboard or device
metaKeyIt returns whether the "meta" key was pressed when the key event was triggered
repeatIt returns whether a key is being hold down repeatedly, or not
shiftKeyIt returns whether the "SHIFT" key was pressed when the key event was triggered
whichIt returns the Unicode character code of the key that triggered the event

Events

And, following are the events that act on keyboardEvent Object −

EventDescription
onkeydownThe event occurs when the user is pressing a key
onkeypressThe event occurs when the user presses a key
onkeyupThe event occurs when the user releases a key

Example

Let us see an example for key property −

 Live Demo

<!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 −

raja
Updated on 30-Jul-2019 22:30:26

Advertisements