Use the var keys = [] global boolean array to check if a key is pressed. Then, to add a global hotkey, use the following function:
window.addGlobalHotkey = function(callback,keyValues){ if(typeof keyValues === "number") keyValues = [keyValues]; var fnc = function(cb,val){ return function(e){ keys[e.keyCode] = true; executeHotkeyTest(cb,val); }; }(callback,keyValues); window.addEventListener('keydown',fnc); return fnc; };
As you can see, this adds a new listener to the 'keydown' event. This listener will first set the corresponding value to keys true, and then run a test if the given keyValues is currently true. Please note that you cannot delete keys[e.keyCode] = true and put it in another listener, because this can lead to a wrong callback order (first check the hotkey and then match the keys). executeHotkeyTest itself executeHotkeyTest also very simple:
window.executeHotkeyTest = function(callback,keyValues){ var allKeysValid = true; for(var i = 0; i < keyValues.length; ++i) allKeysValid = allKeysValid && keys[keyValues[i]]; if(allKeysValid) callback(); };
Finally, you must add another listener to keyup to clear the issued keys from the keys .
window.addEventListener('keyup',function(e){ keys[e.keyCode] = false; });
Now you can add a hotkey to ctrl + x + enter with addGlobalHotkey(callback,[13,17,88]) :
addGlobalHotkey(function(){ document.body.appendChild( document.createElement('div').appendChild( document.createTextNode('Ctrl + x + Enter down') ).parentNode); },[88,13,17]);
Jsfiddle demo
Instead of adding a listener for each hotkey, you can use the global array [[callback1,values1],[callback2,values2],...] .
Important Note : In IE 9, you should use attachEvent instead of addEventListener . Since you are already using jQuery, you can use .on(...) or .keydown .