5

JavaScript Keyboard Event (Arrow Key Example)

 3 years ago
source link: http://siongui.github.io/2012/06/25/javascript-keyboard-event-arrow-key-example/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JavaScript Keyboard Event (Arrow Key Example)

Updated: October 08, 2018

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 += "← ";
      break;
    case Key.UP:
      info.innerHTML += "↑ ";
      break;
    case Key.RIGHT:
      info.innerHTML += "→ ";
      break;
    case Key.DOWN:
      info.innerHTML += "↓ ";
      break;
    default:
      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.


References

[1]Keyboard events | JavaScript Tutorial

[3]JavaScript - Detecting keystrokes - QuirksMode

[4]JavaScript Madness: Keyboard Events


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK