Detect arrow keypress in JavaScript

Detect Arrow Key Press in JavaScript.

In this article, we’ll learn how to detect arrow key presses using JavaScript with a fun little “Arrow Key Detective” game! Every time you press an arrow key, we will display the corresponding arrow and message on the screen. Let’s dive right in and solve this problem step-by-step.

HTML, CSS, and JavaScript to Detect Arrow Key Presses

We will use HTML for structure, CSS for styling, and JavaScript for logic.

Step 1: Create the Basic HTML Structure with included

Start by creating a simple HTML file. We need a container to display the arrow and a message that tells us which key was pressed. Here’s how our HTML structure looks:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Arrow Key Detective</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
        }
        #game-container {
            text-align: center;
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        #arrow-display {
            font-size: 48px;
            margin: 20px 0;
        }
        #message {
            font-size: 18px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div id="game-container">
        <h1>Arrow Key Detective</h1>
        <div id="arrow-display">⬜</div>
        <div id="message">Press any arrow key!</div>
    </div>
</body>
</html>

Step 2: Write the JavaScript Logic to Detect Arrow Keys

Now comes the fun part—detecting the arrow keys! We will use document.addEventListener to listen for key presses. When an arrow key is pressed, we will display the corresponding arrow and update the message accordingly. Here’s the JavaScript code:

<script>
    const arrowDisplay = document.getElementById('arrow-display');
    const message = document.getElementById('message');

    document.addEventListener('keydown', (event) => {
        let arrowKey = '';
        switch(event.key) {
            case 'ArrowUp':
                arrowKey = '⬆️';
                break;
            case 'ArrowDown':
                arrowKey = '⬇️';
                break;
            case 'ArrowLeft':
                arrowKey = '⬅️';
                break;
            case 'ArrowRight':
                arrowKey = '➡️';
                break;
            default:
                arrowKey = '❓';
        }
        
        arrowDisplay.textContent = arrowKey;
        message.textContent = `You pressed: ${event.key}`;
        
        // Prevent default behavior for arrow keys (like scrolling)
        if (event.key.startsWith('Arrow')) {
            event.preventDefault();
        }
    });
</script>

How It Works:

  1. JavaScript: We add an event listener for key presses. When an arrow key is detected, we update the arrow-display with the corresponding arrow symbol (⬆️, ⬇️, ⬅️, ➡️) and show the key name in the message box. We also prevent the default behavior of arrow keys to avoid scrolling the page when they are pressed.

Leave a Comment

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

Scroll to Top