I am curious how I, with the following jQuery im code, writing at the bottom of this question, could implement key combos. How it works so far, it allows the user to create key commands by simply following the usual jQuery syntax and providing an event for the key command, for example:
$(window).jkey('a',function(){ alert('you pressed the a key!'); });
or
$(window).jkey('bc d',function(){ alert('you pressed either the b, c, or d key!'); });
and finally, what I want is the ability to do, but I canโt understand:
$(window).jkey('alt+n',function(){ alert('you pressed alt+n!'); });
I know how to do this outside the plugin (when setting up the keyboard for var false and setting the key, set var true and check if var is true when you press another key), but I donโt know how to do it when You donโt know which keys will be pressed and how many. How to add this support? I want them to be able to do things like alt+shift+a or a+s+d+f if they want to. I just can't figure out how to implement this. Any ideas?
I am going to release this as an open source plugin, and I would like someone to give me the right, work, answer the loan on the blog and in the code myself. Thanks in advance!
(function($) { $.fn.jkey = function(keyCombo,callback) { if(keyCombo.indexOf(' ') > -1){ //If multiple keys are selected var keySplit = keyCombo.split(' '); } else{ //Else just store this single key var keySplit = [keyCombo]; } for(x in keySplit){ //For each key in the array... if(keySplit[x].indexOf('+') > -1){ //Key selection by user is a key combo... what now? } else{ //Otherwise, it just a normal, single key command } switch(keySplit[x]){ case 'a': keySplit[x] = 65; break; case 'b': keySplit[x] = 66; break; case 'c': keySplit[x] = 67; break; //And so on for all the rest of the keys } } return this.each(function() { $this = $(this); $this.keydown(function(e){ if($.inArray(e.keyCode, keySplit) > -1){ //If the key the user pressed is matched with any key the developer set a key code with... if(typeof callback == 'function'){ //and they provided a callback function callback(); //trigger call back and... e.preventDefault(); //cancel the normal } } }); }); } })(jQuery);
javascript jquery plugins keyboard-shortcuts jkey
Oscar Godson
source share