HTML and CSS Reference
In-Depth Information
The following example listens for the keydown event on the text box and shows the
keycode for the pressed key:
document.getElementById("firstNameText").addEventListener("keydown", function () {
document.getElementById("outputText").innerText = window.event.keyCode;
});
Code such as this can be used to filter out invalid characters from being entered into a text
box. With keyboard events, extra properties are available on the event object to help out.
For example, you might need to know whether the Shift key or Control key was also being
pressed. Table 2-4 lists the event object properties for keyboard events.
TABLE 2-4 Event object properties for keyboard events
Property
Description
A Boolean value to indicate whether the Alt key was pressed
altKey
The numeric code for the key that was pressed
keyCode
A Boolean value as to whether the Control key was pressed
ctrlKey
A Boolean value as to whether the Shift key was pressed
shiftKey
EXAM TIP
In some cases, depending on the key, only the keydown event fires. The arrow keys are such
an example: keydown fires but not keyup or keypress .
You can use properties such as ctrlKey with the keyCode event to give the users something
similar to hotkey functionality to automatically navigate the focus to specific fields:
document.onkeydown = function () {
if (window.event.ctrlKey && String.fromCharCode(window.event.keyCode) == 'F')
document.getElementById("firstNameText").focus();
if (window.event.ctrlKey && String.fromCharCode(window.event.keyCode) == 'L')
document.getElementById("lastNameText").focus();
return false;
}
Mouse events
The DOM provides extensive exposure to mouse activity through the mouse events. Table 2-5
describes the available mouse events.
TABLE 2-5 Available mouse events
Event
Description
Raised when the mouse performs a click
click
 
Search WWH ::




Custom Search