Javascript DOM KeyboardEvent which Property

Introduction

Get the Unicode value of the pressed keyboard key:

var x = event.which;

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) {/*w w w.  j av  a2  s .  c  o m*/
  var x = event.which;
  document.getElementById("demo").innerHTML = "The Unicode value is: " + x;
}
</script>
</body>
</html>

The which property returns the Unicode character code of the key that triggered the onkeypress 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, because the key that is pressed on the keyboard is the same.

They have a different character code because the resulting character is different.

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

This property is read-only.




PreviousNext

Related