var ShortcutMan = {};
ShortcutMan.getEventCode = function(evt) {
//IE browsers don't pass the event object as an argument, so get them from the window object
if (!evt)
var evt = window.event;
if (evt.keyCode) //on IE use keycode
var code = evt.keyCode;
else if (evt.which) //on mozilla use wich
var code = evt.which;
if (code >= 65 && code <= 90) //let's just use lower case codes
code = code + 32;
var ctrl = evt.ctrlKey ? 'c' : ''; //is ctrl pressed
var alt = evt.altKey ? 'a' : ''; //is alt pressed
var shift = evt.shiftKey ? 's' : ''; //is shift pressed
return ctrl + alt + shift + code; //put all the pieces together and return the string
}
//a hash to store the actions in code / action pairs
ShortcutMan.keyShortcuts = {};
ShortcutMan.registerShortcut = function(code, action) {
//if the code is not in the correct form, do nothing
if (!/^c?a?s?\d{1,3}$/.test(code))
return;
//store the action in the keyshortcut hash
ShortcutMan.keyShortcuts[code] = action;
}
ShortcutMan.readShortcut = function(evt) {
//convert the event object in a keyboard shortcut code
var code = ShortcutMan.getEventCode(evt);
//if there is an action associated with that keystroke
if (typeof(ShortcutMan.keyShortcuts[code]) == 'function') {
//execute it
ShortcutMan.keyShortcuts[code]();
//and override the browser default behaviour
document.defaultAction = false;
} else //otherwise just tell the browser to keep on what hes doing
document.defaultAction = true;
return document.defaultAction;
}
//attach the readShortcut method to the onkeypress event in the document
document.onkeypress = ShortcutMan.readShortcut;