Skip to main content
4 of 4
edited tags; edited title
200_success
  • 144.2k
  • 22
  • 188
  • 473

jQuery plugin to detect Konami cheat code sequence

How can this be written a bit shorter?

jQuery.konami = function(fn, code) {
    // ↑ ↑ ↓ ↓ ← → ← → B A
    code = code || [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];

    var kkeys = '',
        i = 0;

    $(document).keydown(function(e) {
        var char = String.fromCharCode(e.which).toLowerCase();
        if (char === code[i++]) {
            kkeys += char;

            if (kkeys === code) {
                fn();
                kkeys = '';
                i = 0;
            }
        } else if (e.which === code[kkeys++]) {
            if (kkeys === code.length) {
                fn();
                kkeys = '';
                i = 0;
            }
        } else {
            kkeys = '';
            i = 0;
        }
    });
};
yckart
  • 141
  • 1
  • 1
  • 6