Detecting arrow key presses in JavaScript?


In this article we are going to learn about detecting arrow key presses in JavaScript. Before we jump into the article, let’s discuss few things to know some information.

There is a distinct key code for each key on the keyboard. Here, we'll check to see if the arrow key has been pressed. There are four arrow keys on our keyboard. On our keyboard, we can see, the left, right, up, and download keys. These keys also have a special key code that JavaScript can utilise to determine whether, or not they have been depressed.

The key codes for the left arrow key, up arrow key, right key, and down arrow key are 37, 38, 39, and 40, respectively.

Let’s look into the article to understand more about detecting arrow key presses in JavaScript.

Keydown Event Listener in JavaScript

When a key is pressed, the .onkeydown event handler instructs the compiler to execute a specific function(); by placing an alert("message"), we can display an alert box containing a specific message.

Example

In the following example we are running the script with .onkeydown JavaScript event handler by passing arrow key unique codes.

<!DOCTYPE html>
<html>
<body style="text-align:center;">
   <h1> JavaScript Detecting arrow key presses.</h1>
   <p>click on the output page and then press the arrow key to get event triggered</p>
   <script>
      document.onkeydown = function(event) {
         switch (event.keyCode) {
            case 37:
               alert('Left key');
            break;
            case 38:
               alert('Up key');
            break;
            case 39:
               alert('Right key');
            break;
            case 40:
               alert('Down key');
            break;
         }
      };
   </script>
</body>
</html>

When the script executed, it will make the event that triggers and displays an alert box whenever the user presses the arrow key. For example, if the users click the down arrow key the event triggered and display an alert “down key”.

Example

Let’s consider the another example to detect the arrow key pressed. In this case if we need to observe the output we need to open the console.

<!DOCTYPE html>
<html>
<body>
   <textarea>Click then try the arrows</textarea>
   <script>
      const element = document.querySelector("textarea"),
      ArrowRight = k => {
         console.log(k);
      },
      ArrowLeft = k => {
         console.log(k);
      },
      ArrowUp = k => {
         console.log(k);
      },
      ArrowDown = k => {
         console.log(k);
      },
      handler = {
         ArrowRight,
         ArrowLeft,
         ArrowUp,
         ArrowDown
      };
      element.addEventListener("keydown", e => {
         const k = e.key;
         if (handler.hasOwnProperty(k)) {
            handler[k](k);
         }
      });
   </script>
</body>
</html>

On running the above script, the output window will pop ups, displaying a textarea consisting of text inside. When the user clicks on the textarea and presses the arrow keys the event gets triggered and displays the key pressed by the user in the console.

We can examine the image of the keys pressed by the user.

Example

Considering the following example, we are running a script to detect the arrow key pressed.

<!DOCTYPE html>
<html>
<body>
   <h1> JavaScript Detecting arrow key presses.</h1>
   <p>click on the output page and then press the arrow key to get event triggered</p>
   <script>
      document.addEventListener("keydown", function(event) {
         if (event.key == "ArrowLeft"){
            alert("Left key");
         } else if (event.key == "ArrowUp"){
            alert("Up key");
         } else if (event.key == "ArrowRight"){
            alert("Right key");
         } else if (event.key == "ArrowDown"){
            alert("Down key");
         }
      });
   </script>
</body>
</html>

When the script gets executed, it will generate an output consisting of text along with a prompt on the webpage. If the user clicks on the output window and presses the arrow key, the event gets triggered and displays an alert about the arrow key pressed by the user.

Updated on: 18-Jan-2023

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements