Understanding The JavaScript Event Model (part 2) - Of Keys And Clicks (Page 6 of 10 )
The Event object can also be used to track keyboard events and mouse clicks, and use this information to execute specific actions or commands. Most of this takes place through the Event object's "which" property, which provides information on the key or button pressed. Consider the following example, which demonstrates how this works in Netscape Navigator:
<html>
<head>
<script language="JavaScript">
function whichKey(km)
{
alert(km.which);
}
document.onkeydown = whichKey;
document.onmousedown = whichKey;
</script>
</head>
<body>
</body>
</html>
In this case, the whichKey() function is called every time a key is pressed or a mouse button is clicked. In the case of a key event, the Event object receives the ASCII value of the key pressed; in the case of a mouse click, it receives a number indicating the mouse button clicked (1 for the left button, 3 for the right button).
Internet Explorer has a slightly different way of doing this - take a look at the following variant, which uses the "keyCode" property to get the key code of the pressed key and the "button" property to get the number of the clicked mouse button.
<html>
<head>
<script language="JavaScript">
function whichKey()
{
alert(event.keyCode);
}
function whichButton()
{
alert(event.button);
}
document.onkeydown = whichKey;
document.onmousedown = whichButton;
</script>
</head>
<body>
</body>
</html>
There are a couple of important differences between Internet Explorer and Netscape Communicator when it comes to keyboard and click tracking. The "which" property returns the ASCII value of the key pressed, whereas the "keyCode" property returns the Unicode value. Also, the "keyCode" property is specifically restricted to the keyboard, whereas the "which" property can be used for both keyboard and mouse events.
The "button" property returns an integer corresponding to the number of mouse buttons held down during the event. 0 indicates none, 1 indicates the left button, 2 indicates the right button, and so on.
Next: A Few Modifications >>
More JavaScript Articles
More By Team Melonfire, (c) Melonfire