Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

258
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda