Like this article? We recommend
Field-Level Shortcuts
One of the most common usages of the keyboard shortcuts is the emulation of keyboard sequences used by almost all word processing software: Ctrl-B to make the text bold, Ctrl-I to make it italic, and Ctrl-S to save it. The event handler that would recognize these keystrokes is quite simple:
- We define a dispatch table listing all control characters recognized by the
event handler and the corresponding JavaScript functions:
var textDispatch = { B : makeBold, S : startPreview, I : makeItalic }
- The event handler tests whether the Ctrl key was pressed and whether the
event keycode has a corresponding entry in the dispatch table (the
keycodes for the alphabet letters are equal to their uppercase Unicode
values), in which case the target JavaScript function is invoked and the event
processing is stopped.
function textShortcuts(evt) { var xe = new xEvent(evt); if (! xe.ctrlKey) return; var charCode = String.fromCharCode(xe.keyCode); if (textDispatch[charCode]) { textDispatch[charCode](xe.target,xe); xStopPropagation(evt); xPreventDefault(evt); } }
- The actual word processing work is done in the dispatched JavaScript
functions. In our small example, they just modify a text field or copy the HTML
markup that the user has entered into a separate DIV element; real-life
word processing functions would obviously be more complex.
function makeBold(t,e) {
t.value += "<strong></strong>" } function makeItalic(t,e) { t.value += "<em></em>" } function startPreview(t,e) { var p = xGetElementById("preview"); p.innerHTML = t.value; xAddClass(p,"active"); }
- Finally, the event handler has to be attached to the TEXTAREA
element. Instead of using the onkeydown HTML attribute, we’re
following the guidelines of the
progressive enhancement
and attaching the handler to the input element in the window load
event.
function startEditing() { var txt = xGetElementById("txt"); if (!txt) return; txt.focus(); xAddEventListener(txt,"keydown",textShortcuts); } xAddEventListener(window,"load",startEditing);
You can test the final web page and the associated JavaScript code on my web page.