In this tutorial, we will learn how to detect arrow keypresses in JavaScript.
Arrow keys are commonly used for navigation and interactions within web applications, especially in games, form handling, and custom navigation interfaces.
We will explore how to capture these keypresses and execute specific functions when they are pressed.
Event handler used
The event handler that can be used is either onkeyup() or onkeydown().
Step 1: Setting up HTML code.

- h1, h2 tag are simply for user understanding.
- h3, p tag that is empty in which the output that, the key pressed by the user can will be displayed.
Step 2: Understanding JavaScript code.

- The script tag is opened and two variables were initialized to get those h3, p tag separately.
Step 3: Applying if conditionals.

KeyCodes :
- Up Arrow: keycode 38 or key “ArrowUp”
- Down Arrow: keyCode 40 or key “ArrowDown”
- Left Arrow: keyCode 37 or key “ArrowLeft”
- Right Arrow: keyCode 39 or key “ArrowRight”
- When the event.keyCode is equal its keyCode the correspondent arrow key is displayed in the place of h3 tag
- Also the instruction to press only the arrow key is given in the p tag.
Step 4: Some styling.

Output:

- Since the down arrow is pressed the h3 text content is written as Down Arrow.
So, this is how you can detect arrow keypress in JavaScript.
THANK YOU.