Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

171
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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!');
})

about 4 years ago · Juan Pablo Isaza Relatório

0

Simultaneous keys (like ctrl+Z) is different to a sequence (like 420).

One of many strategies could be to split the sequence into an array and use a copy of it (temp) to shift that sequence when the first element is typed.

let targetSequence = "420".split("")
let temp = [...targetSequence]

document.querySelector("#test").addEventListener("keyup", function(e) {

  if (temp[0] == e.key) {
    temp.shift()
  } else {
    temp = [...targetSequence]
  }
  console.log(temp)

  // If the sequence was done
  if (!temp.length) {
    console.log("--- You did it! ---")
    temp = [...targetSequence]
  }

})
<input id="test">

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda