'How to trigger event by pressing key?
I've created a lame car game in which by clicking a button an image of a car moves to the right a little each time. But now I want to trigger the button by pressing a key. I've used onKeypress and placed it inside the button tag but it isn't working. I tried to figure it out on my own but unfortunately couldn't wrack up the logic for it. Can you guys help me out with this, please?
<div id="racetrack"><img id="user" src="ferrari.jpg"></div>
<button id="pedal" onkeypress="moveCar()">Pedal</button>
function moveCar(){
var car = document.getElementById("user");
var marginLeft = car.style.marginLeft == "" ? "0px" : car.style.marginLeft;
car.style.marginLeft = parseInt(marginLeft) + 100 + "px";
Solution 1:[1]
See a very simple example below. (Try clicking buttons and hitting left/right arrow keys)
I think you'd want to attach a general keydown event to window (or global), rather than attaching to the button. While you can listen for keyboardEvents on a button, you'd need to have the element focused first.
const buttons = document.querySelectorAll('button');
const user = document.querySelector('#user');
let delta = 0;
function move() {
user.style.transform = `translateX(${delta}px)`;
}
function handleClick(e) {
const direction = e.target.dataset.id;
if (direction === 'left') {
delta += -10;
} else {
delta += 10;
}
move();
}
function handleKeydown(e) {
const key = e.code;
if (key !== 'ArrowLeft' && key !== 'ArrowRight') return;
if (key === 'ArrowLeft') {
delta += -10
} else {
delta += 10;
}
move();
}
buttons.forEach(btn => btn.addEventListener('click', handleClick));
window.addEventListener('keydown', handleKeydown);
#racetrack {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
}
#racetrack img {
transition: transform .2s;
}
.controls {
margin-top: 15px;
}
<div id="racetrack">
<img id="user" src="https://picsum.photos/id/237/200/">
<div class="controls">
<button data-id="left">left</button>
<button data-id="right">right</button>
</div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bumhan Yu |
