JS Key Detection Sequence

Check what the user types compared to a secret code that is logged in js.

How?

You can store the keys that are pressed by using a key up function.

  const pressed = [];
const secretCode = 'orange';


window.addEventListener('keyup', (e) => {
  console.log(e.key);
  pressed.push(e.key);
  pressed.splice(-secretCode.length - 1, pressed.length - secretCode.length);
  console.log(pressed);
});

Using the key up function, and e.key we can see what key is pressed. From here we can create an array that has the keys stored in using push().

Now we have an array of stored letters, we can use splice, we want to start at the end of letters using -secretCode.length - 1 from here we want to trim to the max number of the secret codes length. Now when we type over the secret code letter length, it adds the letter to the front, meaning the combination would be incorrect.

Now we can check.

    if(pressed.join('').includes(secretCode)) {
    // your styles
  }

Using join to convert the array to a string, we can use the includes method to check if secretCode is correctly typed from the user.

Things learnt

  1. Pushing key code to array
  2. splice method to get certain string letters
  3. join method to convert array to string
  4. KONAMI CODE

Example code

See the Pen 30 days js key sequence detection (KONAMI CODE) by Harry Beckwith (@fun) on CodePen.


151 0 0