Keyboard Input Lesson

Focus

Keyboard input lets a browser program respond when the user presses or releases keys. JavaScript listens for events such as keydown and keyup, then uses the event object to find which key changed.

Code Runner Challenge

Keyboard Input Lesson

View IPYNB Source
%%js

// CODE_RUNNER: Keyboard Input Lesson

const keys = {};

window.addEventListener("keydown", function(event) {
  keys[event.key] = true;
});

window.addEventListener("keyup", function(event) {
  keys[event.key] = false;
});

function updatePlayer(player) {
  if (keys.ArrowRight) {
    player.x = player.x + 5;
  }
}
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

For games, it is common to store key states in an object. The keydown event marks a key as pressed, and the keyup event marks it as released. The update loop can then check the current state whenever it needs movement.

The keys object remembers whether each key is currently pressed. The updatePlayer function can use that state to move the player.