Keyboard Input

What is keyboard input handling?

Keyboard input handling lets your program respond when the user presses keys. You can detect key presses and trigger code accordingly.

Benefits of keyboard input?

  • Respond to player actions
  • Build interactive games and applications
  • Create real-time control systems
  • Handle multiple keys simultaneously
  • Build responsive user interfaces
// Listening to keyboard events
let keysPressed = {};

document.addEventListener('keydown', function(event) {
    keysPressed[event.key] = true;
});

document.addEventListener('keyup', function(event) {
    keysPressed[event.key] = false;
});

// Check if specific key is pressed
function checkInput() {
    if (keysPressed['ArrowLeft']) {
        console.log("Moving left");
    }
    if (keysPressed['ArrowRight']) {
        console.log("Moving right");
    }
}

What does this code do?

  • Listens for keydown events when key is pressed
  • Listens for keyup events when key is released
  • Stores key states in keysPressed object
  • checkInput() can check which keys are currently pressed
  • Allows detecting multiple simultaneous key presses
// Movement system using keyboard input
let playerX = 100;
let playerY = 300;

document.addEventListener('keydown', function(event) {
    if (event.key === 'ArrowUp' || event.key === 'w') playerY -= 10;
    if (event.key === 'ArrowDown' || event.key === 's') playerY += 10;
    if (event.key === 'ArrowLeft' || event.key === 'a') playerX -= 10;
    if (event.key === 'ArrowRight' || event.key === 'd') playerX += 10;
    
    console.log("Player at (" + playerX + ", " + playerY + ")");
});

What does this code do?

  • Detects arrow keys or WASD keys
  • Updates player position based on key pressed
  • Shows practical game movement system
  • Handles multiple key mappings (arrows or WASD)
  • Demonstrates real-time input handling for games

Try It Yourself

%%js // CODE_RUNNER: keyboard-input document.addEventListener(‘keydown’, (event) => { if (event.key === ‘ArrowUp’) { console.log(“Move up”); } else if (event.key === ‘ArrowDown’) { console.log(“Move down”); } else if (event.key === ‘ ‘) { console.log(“Jump”); } });