Ewebsiteservices

Javascript Key Events with character codes and key codes

Each keyboard character has a unique character code for JavaScript and it helps to not only know these character codes but how to use these codes to handle interactive JavaScript keyboard applications. First off let’s start with getting the character codes for each keyboard button. Below is a simple text box that allows you to type a character in and receive it’s character code to the right of the box.


Once you have your character code implementing it into your interactive application is simple. For example, if you wanted JavaScript to react to a visitor pressing the space button on your website you would use the character code 32 in conjunction with JavaScript to have something happen. You can access the key’s code that was pressed through.

event.keyCode

As an example, if you wanted your entire document to write space when that button was pushed the code would be as follows:

<script type="text/javascript">
function checkKeyCode(keyCode) {
if(keyCode == 32) {
document.write('space');
}
}
</script>
<body onkeydown="checkKeyCode(event.keyCode);">