You can call a function from an element using the onkeydown property. When a key is pressed down get the pressed key, use the keyCode and which event properties.
Note: The onkeypress event is similar to the onkeydown event, but it does not fire for all key types in all browsers.
JavaScript onkeydown keycode example
This HTML example one illustrates the use of the onkeydown event:
<!DOCTYPE html>
<html>
<head>
<script>
function GetChar(event){
var x = event.keyCode;
alert ("The Unicode key code is: " + x);
}
</script>
</head>
<body>
<input size="40" placeholder="Write.." onkeydown="GetChar(event);"/>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this JS keycode code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version