Skip to content

Instantly share code, notes, and snippets.

@blatyo
Created August 28, 2009 19:04
Show Gist options
  • Select an option

  • Save blatyo/177158 to your computer and use it in GitHub Desktop.

Select an option

Save blatyo/177158 to your computer and use it in GitHub Desktop.
var Hotkey = (function(){
var modifiers = ['ctrl', 'shift', 'alt'];
var hotkeys = $H();
return {
add: function(keyCombination, behavior, options){
var keys = keyCombination.split('+');
var mods = keys.union(modifiers);
var key = keys.without.apply(keys, modifiers).reduce();
if(Object.isArray(key)) throw "Error: Hotkey can only contain one key that is not a modifier";
options = Object.extend({
element: document,
bubble: false,
retval: false
}, options || {});
hotkeys.set(keyCombination, {options: options, handler: {
keydown: function(event){
var triggered = Event.hasKeyEvent(Event['KEY_' + key.toUpperCase()])
|| Event.hasKeyEvent(key.charCodeAt(0));
mods.each(function(mod){
triggered = triggered && event[mod + 'Key'];
});
if(triggered) {
behavior(event);
if(!options.bubble) event.stopPropagation();
if(!options.retval) event.preventDefault();
}
}
}});
options.element.observeAll(hotkeys.get(keyCombination).handler);
},
remove: function(keyCombination){
var hotkey = hotkeys.get(keyCombination)
hotkey.options.element.stopObservingAll(hotkey.handler);
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment