Working With the Keyboard in Java Script
By Stephen Bucaro
Using Java Script you can determine which keyboard key the user pressed. You
can use this information to block certain keys, to replace a key's character,
or to perform an action based upon a specific key being pressed. In this article,
I'll provide some basic code for working with the keyboard.
The Internet Explorer and Firefox browsers use slightly different syntax to
capture keyboard events. If you want to determine which key the user pressed
when the mouse pointer was anywhere inside the browser window, Internet Explorer
places the key code in window.event.keyCode", but FireFox passes the key code as
a parameter to the document's onkeypress function.
The code shown below displays the key code in a message box in both Internet
Explorer and Firefox when the user presses a key anywhere in the browser window.
(In other words the browser window has the focus).
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script type="text/javascript">
function keyPressed(e)
{
var key;
if(e) key = e.which;
else key = event.keyCode;
alert(key);
}
document.onkeypress = keyPressed;
</script>
</head>
<body>
</body>
</html>
If you want to determine which key the user pressed inside an element such a
text box, Internet Explorer returns the key code in event.keyCode, but Firefox
returns the key code in event.charCode.
The code shown below displays the key code in a message box in both Internet
Explorer and Firefox when the user presses a key inside a textbox.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script type="text/javascript">
function keyPressed(event)
{
var key;
if(event.keyCode) key = event.keyCode;
else key = event.charCode;
alert(key);
}
</script>
</head>
<body>
<form>
<input type="text" onkeypress="keyPressed(event)">
</form>
</body>
</html>
The key codes being returned are the ASCII codes representing the keys being
pressed. Shown below is an incomplete list of ASCII codes.
symbol | code | symbol | code |
A | 65 | a | 97 |
B | 66 | b | 98 |
C | 67 | c | 99 |
D | 68 | d | 100 |
E | 69 | e | 101 |
F | 70 | f | 102 |
G | 71 | g | 103 |
H | 72 | h | 104 |
I | 73 | i | 105 |
J | 74 | j | 106 |
K | 75 | k | 107 |
L | 76 | l | 108 |
M | 77 | m | 109 |
N | 78 | n | 110 |
O | 79 | o | 111 |
P | 80 | p | 112 |
Q | 81 | q | 113 |
R | 82 | r | 114 |
S | 83 | s | 115 |
T | 84 | t | 116 |
U | 85 | u | 117 |
V | 86 | v | 118 |
W | 87 | w | 119 |
X | 88 | x | 120 |
Y | 89 | y | 121 |
Z | 90 | z | 122 |
|