This example shows how to handle a core set of control keys, that can be used for interaction with accessible JavaScript widgets:
All of these are common, intuitive keystrokes, that can be mapped to particular scripted actions according to what they do. For example, most dynamic menus use the Arrow Keys for internal navigation, while some custom dialogs use the Escape key to close.
Most keys also have default browser actions, and it's sometimes necessary to block the default, to prevent a behavioural conflict. For example, the Up-Arrow and Down-Arrow keys can be used to scroll the page, but when used in dynamic menus this native action must be blocked, so they don't scroll the page at the same time.
So you have to be extremely precise when scripting for these keys — make sure you use the one that's most appropriate for the action, and that your events are filtered so they only apply when they need to. Don't unnecessarily block native actions or stop them from working entirely, and only respond to keystrokes at all when the widget is actually in use.
And never block the Tab key, or you'll trap the user focus!
When scripting for these control keys, there are two different events you can use:
keydown
events, which can be used to block default
actions, and which fire continually if the key is held down
keyup
events, which can't be used to block default
actions, and only fire once
Most browsers don't (and shouldn't) fire the keypress
event for control keys, it's only used for keys which actually insert
a character, like letters and numbers.
Tab into the field below and press any of
the listed control keys. The key's name and keyCode
will be written into the field, and the default action will be
blocked for all except the Tab key:
The JavaScript code for this example can be found in: JS_C_A1.js