- Introduction
- Keyboard Events
- What Was Pressed?
- Event Propagation and Default Action
- Field-Level Shortcuts
- Document-Level Shortcuts
- Summary
Document-Level Shortcuts
The document-level (or web page–level) shortcuts are implemented by attaching the keyboard event handler to the document object. This is the only solution if you want to implement keyboard shortcuts on a web page that has no input elements or hyperlinks that could be focused. If your page has input elements, you have to be a bit more careful:
- The input element keyboard handler and the document-level keyboard handler should not process the same set of keystrokes. If they do, you could utterly confuse the user, as the same keystroke would perform one action if the input element is focused and another action if it’s not.
- If the document-level keyboard handler prevents the default action, it might interfere with the browser’s text-editing capabilities.
I’ll illustrate the second point with an example. Let’s assume that we want to have a counter on the web page that could be incremented and decremented with the arrow keys. (In a real-life application, you could browse through database records instead of changing the counter value.) The keyboard event handler to perform this action is quite simple: We ignore the keydown event if the Ctrl, Alt, or Shift key is pressed; otherwise, we test the two relevant keycodes (up arrow and down arrow). If the event handler recognizes the keycode, it changes the counter, displays the new value, stops the event propagation (not strictly necessary, as this will be a document-level event handler), and prevents the default action.
function changeCounter(evt) { var xe = new xEvent(evt); if (xe.ctrlKey || xe.altKey || xe.shiftKey) return; switch (xe.keyCode) { case 38: cnt++; break; case 40: cnt--; break; default: return; } displayCounter(); xStopPropagation(evt); xPreventDefault(evt); }
As before, the event handler is initialized in the window load event:
xAddEventListener(window,"load",function() { xAddEventListener(document,"keydown",changeCounter); });
The event handler works perfectly (you can test it on my web site), but interferes with the editing capabilities of the TEXTAREA element. Open the sample web page and try to move the cursor in the text input element with the arrow keys. The cursor doesn’t move (due to the xPreventDefault call in the document-level keyboard event handler) and the counter is increased or decreased.