Created
February 15, 2016 23:53
-
-
Save jakerb/14d47ca2170e5ab0deb8 to your computer and use it in GitHub Desktop.
A simple jQuery function to bind key input combinations to a function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* @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