keypress event javascript code example
Example 1: keypress javascript
The keypress event has been deprecated,
you should look to use beforeinput : https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/beforeinput_event
or keydown : https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event
instead.
(And don't forget to like answers that help you !)
Example 2: detect keypress javascript
document.addEventListener("keypress", function onEvent(event) {
if (event.key === "ArrowLeft") {
// Move Left
}
else if (event.key === "Enter") {
// Open Menu...
}
});
Example 3: js when key is pressed
document.addEventListener("keypress", function(event) {
// do stuff
});
Example 4: how to detect a keypress in javascript
window.addEventListener("keydown", (event) => {
console.log(event.key);
});
Example 5: html onkeypress
<input type="text" onkeypress="myFunction()">
Example 6: how do i listen to a keypress in javascript
let b = document.getElementById("body"); //making var for body
b.addEventListener("keydown", (evt) => {//when this happens
console.log(evt.keyCode); //log keycode
});