Charm City Code

Focused on teaching kids to code

Konami Code

2020-12-17 Web Development

Kids love secret codes and one of the most famous secret codes is:
⬆️ ⬆️ ⬇️ ⬇️ ⬅️ ➡️ ⬅️ ➡️ 🅱️ 🅰️

This sequence of button presses was originally used as a cheat code in classic video games developed by Konami. Today the Konami Code can unlock hidden easter eggs in some modern video games and websites. An example is the WWF-UK site, when the code is entered, the panda logo spins a few times.

We can learn to add the Konami Code to our website with just a bit of JavaScript…

const konamiCode = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
let index = 0;
window.addEventListener("keyup", e => {
  const key = parseInt(e.which || e.location);

  if (key === konamiCode[index]) {
    index++;

    if (index === konamiCode.length) {
      alert("Cheat code activated!");
      index = 0;
    }
  } else {
    index = 0;
  }
});

With this code, we put the key codes for the Konami sequence in an array and then check if the user’s keypress equals the correct key in our array. If it does, we increase the index by 1. We continue checking for valid key presses and if the length of the konamiCode array equals the index, we display an alert saying, “Cheat code activated!”

This is just one way to add a bit of fun to a website. if you want to learn more about web development, connect with me on Twitter or try a free web development class at Code&Play.