Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 49 - JavaScript Keyboard Events

JavaScript keyboard events allow you to detect user interactions with the keyboard, such as key presses and releases.

Types of Keyboard Events

  1. keydown – Fires when a key is pressed down.
  2. keyup – Fires when a key is released.
  3. keypress (Deprecated) – Previously used for character keys but now replaced by keydown and keyup.

Syntax

element.addEventListener("keydown", function(event) {
    console.log("Key pressed:", event.key);
});

Example 1: Detecting Key Presses

document.addEventListener("keydown", function(event) {
    console.log("You pressed:", event.key);
});
  • Logs the key that is pressed in the console.

Example 2: Detecting Arrow Key Presses

document.addEventListener("keydown", function(event) {
    if (event.key === "ArrowUp") {
        console.log("Up arrow key pressed");
    } else if (event.key === "ArrowDown") {
        console.log("Down arrow key pressed");
    }
});
  • Detects when the up or down arrow key is pressed.

Example 3: Moving an Element with Keyboard Controls

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Move Box with Arrow Keys</title>
    <style>
        #box {
            width: 50px;
            height: 50px;
            background: red;
            position: absolute;
            top: 50px;
            left: 50px;
        }
    </style>
</head>
<body>
    <div id="box"></div>

    <script>
        let box = document.getElementById("box");
        let position = { top: 50, left: 50 };

        document.addEventListener("keydown", function(event) {
            let step = 10;
            if (event.key === "ArrowUp") position.top -= step;
            if (event.key === "ArrowDown") position.top += step;
            if (event.key === "ArrowLeft") position.left -= step;
            if (event.key === "ArrowRight") position.left += step;

            box.style.top = position.top + "px";
            box.style.left = position.left + "px";
        });
    </script>
</body>
</html>
  • Moves a box on the screen using arrow keys.

Try Your Hand

  1. Create an input field that detects when the user types the letter "A" and logs "A detected!".
  2. Change the background color when the user presses the spacebar.
  3. Detect when the "Enter" key is pressed inside an input field and alert the user.

Key Takeaways

  • keydown fires when a key is pressed.
  • keyup fires when a key is released.
  • Can be used for navigation, games, and interactive UIs.