Skip to content

Instantly share code, notes, and snippets.

@erikringsmuth
Last active August 29, 2015 13:56
Show Gist options
  • Save erikringsmuth/8813413 to your computer and use it in GitHub Desktop.
Save erikringsmuth/8813413 to your computer and use it in GitHub Desktop.
Konami Code JS
// listen for the konami code
function konami(callback) {
	var LEFT = 37, UP = 38, RIGHT = 39, DOWN = 40, A = 65, B = 66, matchedIndex = 0, konami = [UP, UP, DOWN, DOWN, LEFT, RIGHT, LEFT, RIGHT, B, A];
	window.addEventListener('keydown', function(event) {
		event.keyCode === konami[matchedIndex] ? matchedIndex++ : matchedIndex = 0;
		if (matchedIndex === konami.length) {
			callback();
			matchedIndex = 0;
		}
	});
}

// or shorter
function konami(callback) {
	var i = 0;
	window.addEventListener('keydown', function(event) {
		if (event.keyCode !== [38, 38, 40, 40, 37, 39, 37, 39, 66, 65][i++]) i = 0;
		if (i === 10) { callback(); i = 0; }
	});
}

// do something cool!
konami(function() { document.querySelector('body').style.backgroundColor = "blue"; });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment