Konami Code in JavaScript

Recently, many sites (such as espn.com and facebook.com) have added Easter eggs to their JavaScript libraries that are triggered by the old Konami video game code: up up down down left right left right b a enter. While this does not necessarily improve the web architecture, it does make it more fun. To promote more easter eggs like that, I decided to write a simple script that makes integrating the Konami code into your site trivial.

Example 1: KonamiCode Object

/**
 * Konami Code widget, modified from work done by John Resig.
 */
Core.Controller.KonamiCode = (function() {
	// constants
	var _YU = YAHOO.util,
		_CE = _YU.CustomEvent,
		_YE = _YU.Event;

	// local namespace
	var _F = function() {},
		_keyPressed = [],
		_konamiCode = 38,38,40,40,37,39,37,39,66,65,13,
		_that = null;

	// event namespace
	var _E = {
		onKey: function(e) {
			var keyCode = _YE.getCharCode(e);
			_keyPressed.push(keyCode);

			if (0 < = _keyPressed.toString().indexOf(_konamiCode)) {
				_keyPressed = [];
				_that.onCodeEntered.fire();
			}
		}
	};

	// public namespace
	_F.prototype = {

		/**
		 * The event to fire after the Konami code is successfully entered.
		 * @event onCodeEntered
		 */
		onCodeEntered: new _CE(KonamiCode.CodeEntered, null, false, _CE.FLAT)
	};

	_YE.on(document, keydown, _E.onKey);

	_that = new _F();
	return _that;
})();

This requires including YUI for event handling and custom events. The code listens for key strokes on the document, recording the desired keys in the appropriate order. The developer need only subscribe to the public CustomEvent onCodeEntered, allowing any number of callback functions.

Example 2: using onCodeEntered

Core.Controller.KonamiCode.onCodeEntered.subscribe(function() {
	alert(Guten Tag!);
});

This is very simple to use, just include the code snippet in example 1 after including YUI, so no demo page today.
-----------
Modified to use John Resig&rsquot;s logic, as it was simpler.
A new cryptographic version of this widget is available.