Skip to content

Instantly share code, notes, and snippets.

@jakerb
Created February 15, 2016 23:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakerb/14d47ca2170e5ab0deb8 to your computer and use it in GitHub Desktop.
Save jakerb/14d47ca2170e5ab0deb8 to your computer and use it in GitHub Desktop.
A simple jQuery function to bind key input combinations to a function.
/*
* @author Helpy.xyz
* @version 1.0.1
* @info A simple jQuery function to bind key input combinations to a function.
* @todo Implement SHIFT, CTRL and ALT keys.
*/
var combo = {
init:function(selector) {
var that = this;
if(!selector) {
console.warn('You need to bind Combo to a DOM element');
return false;
}
that.listen = selector;
$(that.listen).bind('keypress', function(e) {
var code = e.keyCode || e.which;
if(that.activeKey) {
if(that.combination[that.activeKey] && $.isFunction(that.combination[that.activeKey][code])) {
that.combination[that.activeKey][code]();
that.activeKey = false;
} else {
if(that.counter >= 2) {
that.activeKey = code;
} else {
that.counter++;
}
}
} else {
that.activeKey = code;
}
});
},
on:function(keyA, keyB, func) {
var that = this;
keyA = $.isNumeric(keyA) ? keyA : keyA.charCodeAt(0);
keyB = $.isNumeric(keyB) ? keyB : keyB.charCodeAt(0);
that.combination[keyA] = {};
that.combination[keyA][keyB] = func;
},
};
combo.listen = '';
combo.counter = 0;
combo.activeKey = false;
combo.combination = {};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment