JavaScript | Detecting the pressed arrow key

Sometimes we need to detect the keys and sometimes even detect which keys were pressed. To detect which arrow key is pressed, We are going to look at 2 examples.

  • onkeydown Event:
    This event occurs when someone presses a key (on the keyboard).
    Syntax:

    • in HTML:



      <element onkeydown="newScript" >
      
    • in JavaScript:

      object.onkeydown = function(){newScript};
      
    • in JavaScript using the addEventListener() method:

      object.addEventListener("keydown", newScript);
      
  • addEventListener() method:
    This method attaches an event handler to the document.
    Syntax:

    document.addEventListener(event, function, captureBoolean)
    

    parameters:

    • event: This parameter is required. It specifies the name of the event in string format.
    • function: This parameter is required. It specifies the function to run when the event happens.

      When the event occurs, an event object as a first parameter is passed to the function. Event object’s type depends on the specified event.

    • captureBoolean: This parameter is optional. It specifies the boolean value that tells whether the event should be executed in the capturing or in the bubbling phase. The default value is false and event executed in the bubbling phase and for true event executed in capturing phase.

Example-1: This example detects the arrow key by onkeydown Event by using event.keyCode.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        JavaScript
      | Detecting arrow key presses.
    </title>
</head>
  
<body style="text-align:center;" id="body">
    <h1 style="color:green;">  
            GeeksForGeeks  
        </h1>
    <p id="GFG_UP" style="font-size: 16px;">
        Press an arrow key and click the 
      button to know which key was pressed 
      last time.
    </p>
    <button onclick="gfg_Run()">
        Detect Arrow key
    </button>
    <p id="GFG_DOWN" 
       style="color:green; 
              font-size: 20px;
              font-weight: bold;">
    </p>
    <script>
        var el_up = document.getElementById("GFG_UP");
        var el_down = document.getElementById("GFG_DOWN");
        var str = 'No key pressed';
  
        function gfg_Run() {
            el_down.innerHTML = str;
        }
        document.onkeydown = function(e) {
            switch (e.keyCode) {
                case 37:
                    str = 'Left Key pressed!';
                    break;
                case 38:
                    str = 'Up Key pressed!';
                    break;
                case 39:
                    str = 'Right Key pressed!';
                    break;
                case 40:
                    str = 'Down Key pressed!';
                    break;
            }
        };
    </script>
</body>
  
</html>

chevron_right


Output:

  • Before clicking on the button:
  • After clicking on the button:

Example-2: This example detects the arrow key by adding a eventListener(keydown) to the body by using event.key.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        JavaScript |
      Detecting arrow key presses.
    </title>
</head>
  
<body style="text-align:center;" id="body">
    <h1 style="color:green;">  
            GeeksForGeeks  
        </h1>
    <p id="GFG_UP" style="font-size: 16px;">
        Press an arrow key and click the
      button to know which key was pressed
      last time.
    </p>
    <button onclick="gfg_Run()">
        Detect Arrow key
    </button>
    <p id="GFG_DOWN" 
       style="color:green;
              font-size: 20px;
              font-weight: bold;">
    </p>
    <script>
        var el_up = document.getElementById("GFG_UP");
        var el_down = document.getElementById("GFG_DOWN");
        var str = 'No key pressed';
  
        function gfg_Run() {
            el_down.innerHTML = str;
        }
        document.body.addEventListener('keydown', function(event)
                                       {
            const key = event.key;
            switch (key) {
                case "ArrowLeft":
                    str = 'Left';
                    break;
                case "ArrowRight":
                    str = 'Right';
                    break;
                case "ArrowUp":
                    str = 'Up';
                    break;
                case "ArrowDown":
                    str = 'Down';
                    break;
            }
        });
    </script>
</body>
  
</html>

chevron_right


Output:

  • Before clicking on the button:
  • After clicking on the button:


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.