In this tutorial , We explore how to detect arrow key presses using JavaScript.
Every key on a keyboard has a unique key code, which can be used in JavaScript to identify specific key presses.
On our keyboard there are four keys.We can see left, right, up and down keys on keyboard.
The left arrow key has the key code 37, the up arrow key has the key code 38, the right arrow key has the key code 39,and the down arrow key has the key code 40. We’ll be utilizing these specific codes in our JavaScript code.
You can see a video tutorial in the link provided.
How to detect arrow key press using JavaScript
Here we will be using “onkeydown” event. The “onkeydown” event is used to capture when a key is pressed down.
Detecting the pressed arrow key using “onkeydown” event
Below is the complete code of JavaScript:
<script> document.onkeydown = function(event) { switch (event.keyCode) { case 37: alert("Left arrow key pressed"); break; case 38: alert("Up arrow key pressed"); break; case 39: alert("Right arrow key pressed"); break; case 40: alert("Down arrow key pressed"); break; } } </script>
You can implement this code in any HTML file, and it will work on most modern browsers, including Chrome, Firefox, and Safari.
You run the code on your browser, you will see the alert box whenever you press one of the arrow keys.
Output:
HOPE YOU LIKED THIS TUTORIAL!