Javascript DOM KeyboardEvent keyCode Property

Introduction

Get the Unicode value of the pressed keyboard key.

var x = event.keyCode;

Press a key on the keyboard in the input field to get the Unicode character code of the pressed key.

View in separate window

<!DOCTYPE html>
<html>
<body>
<input type="text" size="40" onkeypress="myFunction(event)">

<p id="demo"></p>

<script>
function myFunction(event) {/*www . jav  a2  s .co m*/
  var x = event.which || event.keyCode;
  document.getElementById("demo").innerHTML = "The Unicode value is: " + x;
}
</script>

</body>
</html>

The keyCode property returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event.

The difference between the two code types:

  • Character codes - A number which represents an ASCII character
  • Key codes - A number which represents an actual key on the keyboard

A lower case "w" and an upper case "W" have the same keyboard code.

In Firefox, the keyCode property does not work on the onkeypress event.

For a cross-browser solution, use the which property together with keyCode.

To convert the returned Unicode value into a character, use the fromCharCode() method.

This property is read-only.




PreviousNext

Related