2.Detect arrow keypress in JavaScript

“Detect arrow keypress in JavaScript”

Introduction

This task involves detecting arrow key presses using JavaScript. The arrow keys (up, down, left, and right) are often used in web applications for navigation or gameplay. By listening for keyboard events, you can handle user input and provide interactive feedback.


Implementation Details

  1. Attach a keydown event listener to the document object to monitor all keypresses.
  2. Use the event.key or event.code property to identify which key was pressed.
  3. Log the detected arrow key press or execute specific logic for each arrow key.

Here’s the implementation:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Detect Arrow Key Press</title>
</head>
<body>
    <h2>Detect Arrow Keypress in JavaScript</h2>
    <p>Press any arrow key to see the result in the console.</p>

    <script>
        document.addEventListener('keydown', (event) => {
            if (event.key === "ArrowUp") {
                console.log("Up arrow key pressed");
            } else if (event.key === "ArrowDown") {
                console.log("Down arrow key pressed");
            } else if (event.key === "ArrowLeft") {
                console.log("Left arrow key pressed");
            } else if (event.key === "ArrowRight") {
                console.log("Right arrow key pressed");
            }
        });
    </script>
</body>
</html>

Testing

  1. Open the code in a browser.
  2. Press the arrow keys (Up, Down, Left, Right) and observe the corresponding messages displayed on the webpage.
  3. Test the functionality across multiple browsers (Chrome, Firefox, Edge, Safari) to ensure compatibility.

Output

  1. Pressing the Up Arrow displays:
    • “You pressed the Up Arrow!”
  2. Pressing the Down Arrow displays:
    • “You pressed the Down Arrow!”
  3. Pressing the Left Arrow displays:
    • “You pressed the Left Arrow!”
  4. Pressing the Right Arrow displays:
    • “You pressed the Right Arrow!”

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top