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

259
Vistas
How do I allow my program to detect keyCode without getting a type-error in Javascript?

I am fairly new to coding and I have been constantly been coming upon one problem. When making a game, such as snake or pong, I tend to use an event listener to listen for a keydown event such as : document.body.addEventListener("keydown", moveSnake);. I then go onto declare the function moveSnake :

function moveSnake(event){
    switch(event.keyCode){
        case 87:
             break;
        case 83:
             break;
        case 65:
            break;
        case 68:
            break;
         default:
             break;
    }
}

I understand there is no code telling the snake what to do yet. Once I do this I get a reoccurring issue. My program stops, and I get an error message in my console that says : Cannot read properties of undefined (reading 'keyCode'). I am using the latest version of google chrome and if someone could tell me what I am doing wrong it would be much appreciated. I have tried declaring the keyCode as a variable, and many other suggestions I have found randomly online but nothing as worked. Thank you!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The .keyCode has been deprecated due to inconsistency on browsers. (https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode)

You can try with the .code, which names the keys as "ArrowUp", "ArrowLeft", "ArrowRight" and "ArrowDown".

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