Detect arrow keypress in JavaScript.

In this tutorial, we will learn how to detect the arrow key press event in JavaScript.

Detecting Keydown Events

We will be using the keydown event on a document object to register when an arrow key is pressed. This event fires when the user presses a key on the keyboard.

Here’s the code to detect arrow key presses:

document.onkeydown= function(event) {
 switch (event.keyCode) {
   case 37: // left arrow
     alert("Left arrow pressed");
     break;
   case 38: // up arrow
     alert("Up arrow pressed");
     break;
   case 39: // right arrow
     alert("Right arrow pressed");
     break;
   case 40: // down arrow
     alert("Down arrow pressed");
     break;
 }
}

Let’s break down the code:

  • We use document.onkeydown= function(event) {… } for the document object This implies that the function would be called every time a key is pressed.
  • Inside this function, we check the value of event with a switch statement. Here are the keyCode numbers of each arrow key:

    Left arrow: 37
    Up arrow: 38
    Right arrow: 39
    Down arrow: 40

  • Based on the key pressed we show a alert message to the user.

Here’s the HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Detect arrow keypress in JavaScript</title>
</head>
<body>
  <script>
    document.onkeydown= function(event) {
     switch (event.keyCode) {
       case 37: // left arrow
         alert("Left arrow pressed");
         break;
       case 38: // up arrow
         alert("Up arrow pressed");
         break;
       case 39: // right arrow
         alert("Right arrow pressed");
         break;
       case 40: // down arrow
         alert("Down arrow pressed");
         break;
     }
    }
  </script>
</body>
</html>

Checking the Code:

Open your index.html file in a web browser. When you press any of the arrow keys, an alert message should pop up indicating which key was pressed.

Leave a Comment

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

Scroll to Top