Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

91
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!