Ask coding questions

← Back to all posts
JS HELP Keydown
r3b0rn (28)

Im making a game, its like a platformer and I want my character to move around everywhere using arrow keys. Can someone show me how to do this

Answered by ruiwenge2 (621) [earned 5 cycles]
View Answer
Comments
hotnewtop
ruiwenge2 (621)

you can do this:

document.addEventListener("keydown", function(e){
  if(e.key == "ArrowLeft"){
    // do something
  } else if(e.key == "ArrowRight"){
    // do something
  } else if(e.key == "ArrowUp"){
    // do something
  } else if(e.key == "ArrowDown"){
    // do something
  }
});
ruiwenge2 (621)

@r3b0rn btw i type elif instead of else if sorry. im used to python. but in javascript use else if.

r3b0rn (28)

@ruiwenge2 i just changed it to if, but thanks!