Konami Code jQuery Plugin

note from Sun Oct 14, 2012

Here is a Konami code handler I implemented as a jQuery plugin. Usage is super easy and you can define the code sequence yourself if you don't like up-up-down-down-left-right-left-right-B-A.

(What is the Konami Code? Check it out!)

(function($){
    $.fn.konami = function(options) {
        if(typeof options == 'undefined') { options = {} }
        if(typeof options.sequence == "undefined") { options.sequence = [38,38,40,40,37,39,37,39,66,65] }
        if(typeof options.onKonami == "undefined") { options.onKonami = function(){alert("Konami");} }
        this.bind("konami", options.onKonami);

        this.data("keyBuffer", []);
        this.data("sequence", options.sequence);
        
        this.bind("keydown", function(e) {
            var keyBuffer = $(this).data("keyBuffer");
            keyBuffer.push(e.keyCode);
            if(keyBuffer.length > options.sequence.length) {
                keyBuffer.shift();
            }
            $(this).data("keyBuffer", keyBuffer);
            
            if(keyBuffer.join("") == options.sequence.join("")) {
                $(this).trigger("konami");
            }
        });
        return this;
    }
})(jQuery);

The plugin can be used like this:

$("body").konami({onKonami: easterEggyFunction});

// or

$("body").konami({
    onKonami: function(e) {
        doSomethingEasterEggy();
    }
});

To use your own key sequence:

// to do something easter eggy when a user enters the word arugula
// supply the keycodes (not ASCII) as an array
$("body").konami({
    onKonami: function(e) {
        doSomethingEasterEggy();
    },
    sequence: [65, 82, 85, 71, 85, 76, 65]
});

To localize to a specific div:

$("#theSpecialDiv").konami({
    onKonami: function(e) {
        doSomethingEasterEggy();
    }
});

Bonus:

Click here to generate keycode sequences!

tags: #javascript #jQuery #konamiCode

What I'm reading now

A friend recommended "The Little Schemer." The book sets out to teach good recursive thinking through the Scheme programming language. It's slow reading for me, but I am quite enjoying it. I'm learning quite a lot from it. Here's a link to it on Amazon where you can read more about it.

JS and jQuery

O'Reilly has a combined JS/jQuery book in their "The Missing Manual" series.