The keyCode property

The keyboard events have a property called keyCode. This property returns an Unicode key code of the key which triggered the onkeydown or onkeyup events and an Unicode character code for onkeypress event. The Unicode keycode represents the actual key which triggered the event, i.e. ‘a’ or ‘A’ is same in keycode. The Unicode character code is the ASCII value of the character. ‘a’ and ‘A’ represents different character codes. 

When an onkeypress event occurs the character code of the key can be returned. It can be used, for instance, to determine if the user has pressed an input character key or a functional key. 

The keyCode property is in the process of deprecation while the key or keyIdentitfier property is used instead of this from DOM Level 3 on. Hence for cross-browser functionality, the keyCode can be written as:

Syntax for keyCode property

function eventHandler(event){
    if(event.key != undefined){
    //Handle event here
}
else if(event.keyIdentifier != undefined){
    //Handle event here
}
else if(event.keyCode != undefined){
    //Handle event here
}
}
<input type=”text” onkeyup = “eventHandler(event)”>

The charCode property

 When an onkeypress event occurs, the keyboard event property called a charCode property returns the ASCII character of the key which caused the event. If the charCode is used with events other than keypress, it returns 0. IE 9+, Firefox, Chrome and safari supported this property. For previous versions it has to be used with the keyCode property.

The charCode property is a deprecated property and with the DOM level 3 the key property is used in it’s place. For cross-browser functionality, the charCode can be written as:

Syntax for charCode property

function eventHandler(event){
    if(event.charCode || event.keyCode){
    //Handle event here
}
}
<input type=”text” onkeypress = “eventHandler(event)”>

The fromCharCode() function

To get the character back from the keyCode or charCode, the fromCharCode() function may be used:

var x = event.keyCode || event.charCode; 

var str = String.fromCharCode(x);

Example with keyCode and charCode properties

 

›› go to examples ››