How to Detect Arrow Keys in Javascript
In this tutorial, you will learn how to detect arrow keys in javascript. In a standard keyboard layout, we have 4 arrows left, right, up, and down. The arrow keys are located right before the numpad on the keyboard. They are generally used to change cursor position in a textbox as well as help in scrolling a webpage.
Whenever we press an arrow key or any other key on the keyboard, certain keyboard events are triggered. In the event handler function, the event object contains details about the keyboard event. The event object has a key
property that can reveal which key has been pressed by the user.
To keep things simple, we are going to monitor keydown
event and in the event handler function, we will verify whether an arrow key is pressed or not.
In the following example, we have an input field. As soon as the user presses an arrow key while typing in the input field, we will display a message on the screen. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 3 elements in the HTML file (
div
,h1
, andtextarea
). - The
div
element is just a wrapper for the rest of the elements. We are usingstyle
attribute withdiv
element to center align the child elements. - The
innerText
for theh1
element is“Result”
. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div style="text-align: center"> <textarea cols="50" rows="5" placeholder="Enter Text"></textarea> <h1>Result</h1> </div> <script src="script.js"></script> </body> </html>
Javascript
- We have selected the
textarea
element andh1
element usingdocument.querySelector()
method and stored them in theinput
andresult
variables respectively. - We have attached
keydown
event listener to thetextarea
element. - In the event handler function, we are using
switch
statement andkey
property of the event object to verify which arrow key is pressed or not. - Depending upon the result of verification, we are updating
innerText
of theh1
element.
let input = document.querySelector("textarea"); let result = document.querySelector("h1"); input.addEventListener("keydown", (e) => { switch (e.key) { case "ArrowLeft": result.innerText = "Left Arrow"; break; case "ArrowRight": result.innerText = "Right Arrow"; break; case "ArrowUp": result.innerText = "Up Arrow"; break; case "ArrowDown": result.innerText = "Down Arrow"; break; } });