Syntax error HTML DOM KeyboardEvent key Property

HTML DOM KeyboardEvent key Property



The KeyboardEvent key property returns the key identifier corresponding to the key pressed using an event.

Syntax

Following is the syntax −

Returning latest typed character’s identifier −

event.key

Example

Let us see an example for KeyboardEvent 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 −

Updated on: 2019-07-30T22:30:26+05:30

95 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements