Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

201
Vistas
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";
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda