Thursday, November 19, 2009

Konami Code in JavaScript

Yesterday I came to know about this thing called a Konami Code and about how many websites use it as an easter egg!

So I decided to write up my own JavaScript version of this Konami Code.  You can download the normal, unpacked version for development or the packed version for production.

Click here to view a demo


To use the code, following these instructions:

1. Download the konami.js file from one of the above-mentioned links and add it to your page:

<script src="konami.js"></script>

This will create a konamiCode object in your website, which can be used in multiple ways. The konamiCode object takes 2 parameters: combination (an array of keyCodes) and a callback function.

The combination parameter can be skipped and if it is skipped, the default combination will be the Konami Code (UP, UP, DOWN, DOWN, LEFT, RIGHT, LEFT, RIGHT, B, A)

2. The simplest way to enable the Konami Code for your website, is like such:

konamiCode(function () {
    alert('You entered the code!');
}).start();

This will start the Konami code listener.

3. To stop listening for code input, store the konamiCode in a variable and call it's stop method:

var konami = konamiCode(function () {
                 alert('You entered the code!');
             }).start();

//...

konami.stop(); // <== stop listening

4. To use a different combination, enter an array as the first parameter of the konamiCode function:

konamiCode([38, 40, 37, 39, 52, 53], function () {
    alert('You entered the code!');
}).start();

The combination listed above is UP, DOWN, LEFT, RIGHT, 4, 2
As you can see, the elements of the array are the Key Codes of the keys, not the letters themselves. Use this website to convert from a key-press to a Key Code



Here is the unpacked code:

/*
 * Konami Code in Javascript
 * Andreas Grech
 * http://blog.dreasgrech.com
 *  v 1.1 (20091119)

 Keycodes for the Konami Code
 UP    : 38
 DOWN  : 40
 LEFT  : 37
 RIGHT : 39
 B     : 66
 A     : 65
*/

var konamiCode = function(combination, callback) {
 var lastCorrectInput = - 1,
 isActive = 0,
 o = {};
 if (typeof combination === "function") {
  callback = combination;
 }
 if (Object.prototype.toString.call(combination) !== "[object Array]") {
  combination = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
 }
 o.start = function() {
  if (isActive) {
   return;
  }
  isActive = 1;
  document.onkeyup = function(e) {
   var code;
   if (!isActive) {
    return;
   }
   code = window.event ? window.event.keyCode: e.which;
   if (combination[++lastCorrectInput] === code) {
    if (lastCorrectInput === combination.length - 1) {
     if (callback && typeof(callback) === "function") {
      callback();
     }
    }
    return;
   }
   lastCorrectInput = - 1;
  };
  return o;
 };
 o.stop = function() {
  isActive = 0;
  return o;
 };
 return o;
};