All Articles

Key Sequence Detection Javascript

This is day 12 in my #javascript30 journey. This is the free course from Wes Bos that lets you brush up on your JavaScript skills via 30 projects.

Yesterday we created our very own Custom HTML5 Video Player. You can keep track of all the projects we’re building here.

Today we’re exploring Key Sequence Detection (KONAMI CODE)


Day 12 - Key Sequence Detection (KONAMI CODE)

First, what the heck is the KONAMI CODE?

It is a sequence of buttons that are used to unlock easter eggs or enable a cheat code. You can read more about the Konami Code but it is a sequence like: ↑ ↑ ↓ ↓ ← → ← → B A

You can use the Konami Code to access Easter Eggs on the Buzzfeed website. Simply go there and type ↑ ↑ ↓ ↓ ← → ← → B A on your keyboard.


Now it’s time for us to create an Easter Egg. YAY!

First we need to decide on our secret code. I’m going to go with ‘stef.ninja’.

Next we can create an event listener to capture all of the ‘keyup’ events. Once we have captured all of the keys we will store them in an array and compare them to our secret code. We also need to splice the array when it reaches the maximum length of our secret code so we’re not inadvertently creating a keylogger.

If we find a match between the secret code we can use the Cornify script to render random unicorns and rainbows onto the page.

Let’s put it all together:

//Load the cornify script into the head.
http://www.google-analytics.com/ga.js"> type="text/javascript" src="">http://www.cornify.com/js/cornify.js">  

Then in a script tag:

const pressed = []  
const secretCode = 'stef.ninja'  
window.addEventListener('keyup', (e) => {  
  pressed.push(e.key)
  pressed.splice(-secretCode.length - 1, pressed.length - secretCode.length)
  if(pressed.join('').includes(secretCode)) {
    cornify_add()
  }
})

Then when we type the secret code:

UNICORNS


That’s all of todays lesson. Instead of posting this on to my projects page I have added this to my blog. You can now type stef.ninja anywhere on the page to call a Unicorn or Rainbow into existance. Try it now.

You can keep track of all the projects in this JavaScript30 challenge here.