JavaScript 30 — Day 12 — Key Sequence Detection (Konami Code)

Steven Chen
2 min readDec 10, 2021

I’m a day behind so today will be a double-header.

Thankfully Day 12 is a quick one.

Essentially we are trying to capture and detect a key sequence. This combined with the Cornify JS file will add a fun surprise to the screen if the sequence has been detected.

It’s pretty straight forward. Just using an array (let’s call it pressed) and pushing new values to it to get a sequence of keypresses. You’ll want to remove extraneous keypresses, beyond the length of your secret key sequence, from your pressed array otherwise the logic trying to compare them will get wrong and/or unwieldy.

My approach (top) vs. Wes’ approach (bottom)

Nothing wrong with doing things a little different.

I’m not a fan of the kind of messy math logic in the .splice() line in Wes’ code. I used a quick conditional and a .shift(), because while the name of the method itself is bad, once you know it, it makes sense.

Of course mine required a little extra setup, creating a hard-coded code array with keycodes because I was going keypresses that weren’t just letters and writing out all the codes (vs. keyCodes) was a little tedious.

Please Note:

  • Don’t actually use the Konami Code (Up, Up, Down, Down, Left, Right, Left, Right, B, A) because the included Cornify JS file uses this code and it’s broken. Once the Konami Code has been entered it adds some fun stuff to the page as expected, but each subsequent single keypress, no matter what key it is, adds another success which makes no sense in the context of what we’re looking for.
  • So just follow Wes’ example, use a different code and then call the cornify_add() function to your logic.
  • Even if you refresh the Cornify count is kept on your page using cookies. For testing purposes if you want to reset the count:
    - You could open the link in an Incognito Window
    - Clear your cookies through the browser, or
    - Just toss something like the command below into your console.
document.cookie = 'cornify=0'

--

--