JavaScript - Shortcut Keys
Jump to navigation
Jump to search
Contents
About
NOTE: This page is a daughter page of: JavaScript
For certain interfaces you might want to insert shortcut keys (eg: ctrl+s | arrow keys) to a webpage. Below are some examples of setting up shortcut keys.
Setting up KeyPress Events using the DOM
The following code should work nicely on for most browsers:
document.onkeypress = function(e) {
if (!e) e = window.e;
var code = (e.charCode && e.keyCode == 0) ? e.charCode : e.keyCode;
var charVal = String.fromCharCode(code);
alert('code=' + code + ' charVal=' + charVal); // To help you work out what key was pressed.
switch (charVal) {
case ('1'): // [1] or [,] for first option.
case (','):
alert('Option 1 pressed');
break;
case ('p'): // [p] for a different option.
alert('Option P pressed');
break;
}
};
Note that "onkeypress" is a better option then "onkeydown" as the latter often has weird syntax for
Setting up KeyPress Events using Closure
For more versatility you can use Google's closure library which includes a goog.ui.KeyboardShortcutHandler used in their demo as follows:
goog.require('goog.dom');
goog.require('goog.events.KeyCodes');
goog.require('goog.ui.KeyboardShortcutHandler');
function showTriggered(event) {
alert('Shortcut triggered: ' + event.identifier);
}
var shortcutHandler = new goog.ui.KeyboardShortcutHandler(document);
var NONE = goog.ui.KeyboardShortcutHandler.Modifiers.NONE;
var CTRL = goog.ui.KeyboardShortcutHandler.Modifiers.CTRL;
var SHIFT = goog.ui.KeyboardShortcutHandler.Modifiers.SHIFT;
var ALT = goog.ui.KeyboardShortcutHandler.Modifiers.ALT;
var META = goog.ui.KeyboardShortcutHandler.Modifiers.META;
shortcutHandler.registerShortcut('A', 'a');
shortcutHandler.registerShortcut('T E S T', 't e s t');
shortcutHandler.registerShortcut('SHIFT_F12', 'shift+f12');
shortcutHandler.registerShortcut('CTRL_A', goog.events.KeyCodes.A, CTRL);
shortcutHandler.registerShortcut('ENTER', goog.events.KeyCodes.ENTER);
goog.events.listen(
shortcutHandler,
goog.ui.KeyboardShortcutHandler.EventType.SHORTCUT_TRIGGERED,
showTriggered);
NOTE: The html file itself must look like this:
<head>
<script src="../base.js"></script>
<script src="../LINK_TO_YOUR_JS_FILE_HERE.js"></script>
</head>
<body>
Press a shortcut key ('a', 'goog' or a few others).
</body>
Links
- Wikipedia entry - very good overview of javascript syntax
- Google's closure library