JS Key Detection Sequence

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


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

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

window.addEventListener('keyup', (e) => {
  pressed.splice(-secretCode.length - 1, pressed.length - secretCode.length);

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

Example code

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