Languages
[Edit]
EN

JavaScript - detect when arrow key was pressed

6 points
Created by:
Wiktor-Sribiew
830

In this article, we would like to show you how to detect when the arrow key was pressed using JavaScript.

The main idea of how to detect the arrow key is to check the key code when the key event occurred.

Key codes:

Key nameKey code
(event.key, event.code)
Deprecated key code
(event.keyCode)
Left arrowArrowLeft37
Up arrowArrowUp38
Right arrowArrowRight39
Down arrowArrowDown40

 

Practical example

Edit

In the below example, we use some legacy function that lets to get key code. The main reason why that approach was used, is the time when event.key and key.code were introduced in the major web browsers (around 2016-2017). To see the result, each arrows key is handled and displayed a message in the console.

Example 1:

Edit

Example 2:

Edit

 

References

Edit
  1. KeyboardEvent.key - MDN Docs
  2. KeyboardEvent.code - MDN Docs

  3. KeyboardEvent.keyCode - MDN Docs
  4. Document: keydown event - MDN Docs
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join