0
How do I give computer keys a function in Javascript ?
I want to use computer keys for a game to make it easier to control movement, but I don't know. Is it even possible? Please help.
4 odpowiedzi
+ 3
yes, it is possible.
I don't know what solution are you looking for, but you can find an example here:
https://medium.com/coding-beauty/javascript-simulate-keypress-9fcd5a31ff20
I hope this helps
+ 2
Add an event listener on the document for keydown and listen to the keyCode or value of the key pressed to determine if the key represents an action or not. example:
window.addEventListener(
"keydown",
(event) => {
if (event.defaultPrevented) {
return; // Do nothing if the event was already processed
}
switch (event.key) {
case "ArrowDown":
// Do something for "down arrow" key press.
break;
case "ArrowUp":
// Do something for "up arrow" key press.
break;
case "ArrowLeft":
// Do something for "left arrow" key press.
break;
case "ArrowRight":
// Do something for "right arrow" key press.
break;
case "Enter":
// Do something for "enter" or "return" key press.
break;
case " ":
// Do something for "space" key press.
break;
case "Escape":
// Do something for "esc" key press.
break;
}
})
0
how do i add a event listener and find the KeyCode value?
0
Paxton Programer the code is written above, to check the key code for each key, you should replace the switch function with either a console.log or alert function to see the keyCode after the event is triggered:
console.log(event.key + " has keyCode: "+event.keyCode)