Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

257
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!