JavaScript | Detecting the pressed arrow key - GeeksforGeeks

20 May, 2019
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);

in HTML:<element onkeydown="newScript" >

<element onkeydown="newScript" >

in JavaScript:object.onkeydown = function(){newScript};

object.onkeydown = function(){newScript};

in JavaScript using the addEventListener() method:object.addEventListener("keydown", newScript);

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.
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.
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.
<!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>
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.
<!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>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to Use the JavaScript Fetch API to Get Data?
Difference Between PUT and PATCH Request
Express.js express.Router() Function
How to set input type date in dd-mm-yyyy format using HTML ?
Installation of Node.js on Linux
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?