JavaScript Keyboard Event (Arrow Key Example)

This post will give an example for detecting arrow keys using JavaScript. For general keyboard event, it is very easy to achieve by extending the example in this post (also see references below). Try demo first:

Press Arrow Key or Any Other Key:

Source Code for Demo (HTML):

Press Arrow Key or Any Other Key:<br><br>
<div id="info"></div>

Source Code for Demo (JavaScript):

var Key = {
  LEFT:   37,
  UP:     38,
  RIGHT:  39,
  DOWN:   40

 * old IE: attachEvent
 * Firefox, Chrome, or modern browsers: addEventListener
function _addEventListener(evt, element, fn) {
  if (window.addEventListener) {
    element.addEventListener(evt, fn, false);
  else {
    element.attachEvent('on'+evt, fn);

function handleKeyboardEvent(evt) {
  if (!evt) {evt = window.event;} // for old IE compatible
  var keycode = evt.keyCode || evt.which; // also for cross-browser compatible

  var info = document.getElementById("info");
  switch (keycode) {
    case Key.LEFT:
      info.innerHTML += "&larr; ";
    case Key.UP:
      info.innerHTML += "&uarr; ";
    case Key.RIGHT:
      info.innerHTML += "&rarr; ";
    case Key.DOWN:
      info.innerHTML += "&darr; ";
      info.innerHTML += "SOMEKEY ";

_addEventListener('keydown', document, handleKeyboardEvent);

There are three events related to keyboards: onkeydown, onkeypress, onkeyup. To detect arrow keys, please use onkeydown (see [2]).

According to the KeyboardEvent documentation on MDN, the use of event.keyCode is deprecated. We should use event.key instead. If you need to support very old browsers, use the example in this post. Otherwise see [5] for the new example of event.key.


[1]Keyboard events | JavaScript Tutorial
[2]keyboard events - Detecting arrow key presses in JavaScript - Stack Overflow
[3]JavaScript - Detecting keystrokes - QuirksMode
[4]JavaScript Madness: Keyboard Events
[5]JavaScript Arrow Key Example via event.key in Keyboard Event