Detect Arrow key press using javascript

<!DOCTYPE html>
<html lang=”en”>
<head>
    <meta charset=”UTF-8″>
    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
    <title>Arrow Key Detection</title>
    <style>
        /* Simple styling for the display area */
        #display {
            font-size: 24px;
            text-align: center;
            margin-top: 20px;
            padding: 10px;
            border: 2px solid #333;
            width: 200px;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <h2 style=”text-align: center;”>Press an Arrow Key</h2>
    <div id=”display”>Waiting for key press…</div>
    <script>
        // Get the display element
        const display = document.getElementById(“display”);
        // Add an event listener to detect arrow key presses
        document.addEventListener(“keydown”, function(event) {
            switch(event.key) {
                case “ArrowUp”:
                    display.textContent = “Up arrow pressed”;
                    break;
                case “ArrowDown”:
                    display.textContent = “Down arrow pressed”;
                    break;
                case “ArrowLeft”:
                    display.textContent = “Left arrow pressed”;
                    break;
                case “ArrowRight”:
                    display.textContent = “Right arrow pressed”;
                    break;
                default:
                    display.textContent = “Press an arrow key”;
                    break;
            }
        });
    </script>
</body>
</html>

Leave a Comment

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

Scroll to Top