HTML DOM KeyboardEvent code Property


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

Note − Use key property instead for accurate results

Syntax

Following is the syntax −

Returning latest typed character’s code −

event.code

Example

Let us see an example for KeyboardEvent code property −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<title>KeyboardEvent code</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-code</legend>
<label>Press a key:
<input type="text" id="textSelect" onkeypress="getEventData(event)" autofocus>
</label>
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
   var divDisplay = document.getElementById("divDisplay");
   var textSelect = document.getElementById("textSelect");
   function getEventData(InputEvent) {
      divDisplay.textContent = 'Pressed key: '+InputEvent.code;
   }
</script>
</body>
</html>

Output

This will produce the following output −

Before typing anything in the text field −

After typing ‘\’ in the text field −

After typing ‘H’ in the text field −

Updated on: 30-Jul-2019

54 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements