Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Detect combination of user input using JavaScript

I’m trying to make an alert popup when I press a sequence of keys on my website, for example if I write "420" on my keyboard I want a message to popup saying "You made it" or something. I get it when I use only 2 keypresses using this:

  if (e.ctrlKey && e.keyCode == 90) {
    alert("Sweet");
  }
});

Which is the CTRL-key + letter Z, but I cant seem to understand how to make it work if I want it to be the correct sequence of 4 2 0 or something similar. And I’m only allowed to use JavaScript.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For that to work, you need to keep track of keys pressed.

Here, I add every key pressed to a variable str at that variable’s end, and then cut off everything except the last 3 characters.

let str = '';

window.addEventListener('keyup', function(event) {
  str = `${str}${event.key}`.substr(-3);
  if (str === '420') console.log('You made it!');
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading