Detecting arrow key presses in JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

To detect the arrow key when it is pressed, use onkeydown in JavaScript.

The button has key code. As you know the left arrow key has the code 37. The up arrow key has the code 38 and right has the 39 and down has 40.

Example

Following is the code −

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
</body>
<script>
   document.onkeydown = function (event) {
      switch (event.keyCode) {
         case 37:
            console.log("Left key is pressed.");
            break;
         case 38:
            console.log("Up key is pressed.");
            break;
         case 39:
            console.log("Right key is pressed.");
            break;
         case 40:
            console.log("Down key is pressed.");
            break;
      }
   };
</script>
</html>

To run the above program, save the file name anyName.html(index.html). Right click on the file and select the option “Open with live server” in VS Code editor.

Output

Here, I have pressed the up arrow key. This will produce the following output on console −

raja
Updated on 27-Oct-2020 10:01:06

Advertisements