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

95
Visualizações
Keypress event intercepted 40 times even though I press the key only once in Javascript

I want to intercept the event "keypress" with javascript through the following code:

document.addEventListener("keypress", (e) => {
    if (e.key === "a") {
        console.log("You pressed the key a");
    }
}

The code actually works. The problem is that even though I press the a letter once, the string "You press the key a" is printed in my console 40 times. It should be the behaviour of keydown, not keypress.

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

0

As documented by the Developer Mozilla documentation, keypress feature is no longer supported.

Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible.

With this little context I cannot find the problem, you could start by changing it with the 'keydown' event and see if it works.

about 4 years ago · Juan Pablo Isaza Relatório

0

This is my solution. I took the code away from the constructor that is called continuously an put it in a react hook.

const onKeyPress = (e) => {
    if (e.key === "a") {
        console.log("You pressed the key a");
    }
};

useEffect(() => {
    document.addEventListener("keypress", onKeyPress);
    return () => {
        document.removeEventListener("keypress", onKeyPress);
    }
}, []);
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