[javascript] Detecting arrow key presses in JavaScript

With key and ES6.

This gives you a separate function for each arrow key without using switch and also works with the 2,4,6,8 keys in the numpad when NumLock is on.

_x000D_
_x000D_
const element = document.querySelector("textarea"),_x000D_
  ArrowRight = k => {_x000D_
    console.log(k);_x000D_
  },_x000D_
  ArrowLeft = k => {_x000D_
    console.log(k);_x000D_
  },_x000D_
  ArrowUp = k => {_x000D_
    console.log(k);_x000D_
  },_x000D_
  ArrowDown = k => {_x000D_
    console.log(k);_x000D_
  },_x000D_
  handler = {_x000D_
    ArrowRight,_x000D_
    ArrowLeft,_x000D_
    ArrowUp,_x000D_
    ArrowDown_x000D_
  };_x000D_
_x000D_
element.addEventListener("keydown", e => {_x000D_
  const k = e.key;_x000D_
_x000D_
  if (handler.hasOwnProperty(k)) {_x000D_
    handler[k](k);_x000D_
  }_x000D_
});
_x000D_
<p>Click the textarea then try the arrows</p>_x000D_
<textarea></textarea>
_x000D_
_x000D_
_x000D_