Skip to content

Instantly share code, notes, and snippets.

@dncrews
Forked from Problematic/ComboBreaker.js
Created November 9, 2012 21:57
Show Gist options
  • Select an option

  • Save dncrews/4048539 to your computer and use it in GitHub Desktop.

Select an option

Save dncrews/4048539 to your computer and use it in GitHub Desktop.
Simple key-combo detector. Uses jQuery
(function($) {
$.fn.comboBreaker = function(options) {
var index = 0, timeout = null, dfd = $.Deferred();
options = $.extend({}, $.fn.comboBreaker.defaults, options);
if (! options.combo) {
throw new Error("combo not set");
}
$(this).keyup( function(e) {
// for some reason, jQuery always gives us back the upper-case
// ASCII value for e.which, which brings us to:
var expected = options.keyMap[options.combo[index]] ||
options.combo[index].toUpperCase().charCodeAt();
if (e.which === expected) {
clearTimeout(timeout);
if (index === options.combo.length -1) {
dfd.resolve();
index = 0;
return;
}
index++;
timeout = setTimeout(function() {
index = 0;
}, options.resetTime);
}
});
return dfd.promise();
};
$.fn.comboBreaker.defaults = {
resetTime : 1000,
keyMap : {
'enter': 13,
'esc': 27,
'left': 37,
'up': 38,
'right': 39,
'down': 40
}
};
})(jQuery);
$(document).comboBreaker({
combo : ["up", "up", "down", "down", "left", "right", "left", "right", "b", "a", "enter"]
}).done(
function () {
console.log('CCCCCOMBO BREAKER!');
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment