JavaScript Arrow Key Example via event.key in Keyboard Event
This morning I read the KeyboardEvent documentation on MDN, and found that event.keyCode is deprecated, so I re-write the example of detecting arrow keys [1] in JavaScript again to use event.key in this post. If you need to support old browsers, please refer to my previous post.
There are three events related to keyboards: onkeydown, onkeypress, onkeyup. To detect arrow keys, please use onkeydown (see [4]).
In the example, the keydown event of document is listened. If users press any key, the event handler will be triggered. In the handler, the key property of of (keyboard) event will be checked to see which key is pressed.
Source Code for Demo (HTML):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <!doctype html> <html> <head> <meta charset="utf-8"> <title>JavaScript Arrow Key Detection Demo</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> Press Arrow Key or Any Other Key:<br> <textarea id="info" rows="20" cols="80"></textarea> <script src="app.js"></script> </body> </html> |
Source Code for Demo (JavaScript):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 'use strict'; var Key = { LEFT: "ArrowLeft", UP: "ArrowUp", RIGHT: "ArrowRight", DOWN: "ArrowDown" }; function handleKeyboardEvent(event) { var info = document.getElementById("info"); switch (event.key) { case Key.LEFT: info.value += "LEFT "; break; case Key.UP: info.value += "UP "; break; case Key.RIGHT: info.value += "RIGHT "; break; case Key.DOWN: info.value += "DOWN "; break; default: info.value += "SOMEKEY "; } } document.addEventListener("keydown", handleKeyboardEvent); |
Tested on:
- Chromium Version 55.0.2883.87 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)
- Mozilla Firfox 51.0.1 (64-bit)
References:
[1] | JavaScript Keyboard Event (Arrow Key Example) |
[2] | KeyboardEvent.key - Web APIs | MDN |
[3] | javascript switch - Google search |
[4] | keyboard events - Detecting arrow key presses in JavaScript - Stack Overflow |