Reputation: 3037
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.
Upvotes: 0
Views: 94
Reputation: 3037
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);
}
}, []);
Upvotes: 0
Reputation: 66
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.
Upvotes: 1