65

I want to take keyboard input in JavaScript, where arrow keys, when pressed, will result in the change in shape of a particular shape. How do I take the input of any of the keys in JavaScript?

Alex
  • 163
  • 7
Hick
  • 35,524
  • 46
  • 151
  • 243

5 Answers5

108

You can do this by registering an event handler on the document or any element you want to observe keystrokes on and examine the key related properties of the event object.

Example that works in FF and Webkit-based browsers:

document.addEventListener('keydown', function(event) {
    if(event.keyCode == 37) {
        alert('Left was pressed');
    }
    else if(event.keyCode == 39) {
        alert('Right was pressed');
    }
});

DEMO

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 3
    theres anything that I can do to capture Backspace but prevent browser to "Go Back" ? – Vitim.us Nov 14 '11 at 18:54
  • @Vitimtk: Sorry, I don't really have time now, but have a look at these questions: http://stackoverflow.com/search?q=javascript+disable+backspace+navigation – Felix Kling Nov 14 '11 at 19:38
  • 4
    Using event.preventDefault() is probably what you want. As the name suggests, it prevents whatever the default behavior would be for a given event, in this case a backspace keyboard event. This goes into more detail: http://stackoverflow.com/questions/1495219/how-can-i-prevent-the-backspace-key-from-navigating-back – Max Strater May 02 '14 at 23:01
  • 4
    keyCode is deprecated https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode – mrtnmgs Mar 27 '19 at 15:05
21

You should register an event handler on the window or any element that you want to observe keystrokes on, and use the standard key values instead of keyCode. This modified code from MDN will respond to keydown when the left, right, up, or down arrow keys are pressed:

window.addEventListener("keydown", function (event) {
  if (event.defaultPrevented) {
    return; // Do nothing if the event was already processed
  }

  switch (event.key) {
    case "ArrowDown":
      // code for "down arrow" key press.
      break;
    case "ArrowUp":
      // code for "up arrow" key press.
      break;
    case "ArrowLeft":
      // code for "left arrow" key press.
      break;
    case "ArrowRight":
      // code for "right arrow" key press.
      break;
    default:
      return; // Quit when this doesn't handle the key event.
  }

  // Cancel the default action to avoid it being handled twice
  event.preventDefault();
}, true);
// the last option dispatches the event to the listener first,
// then dispatches event to window
SK-the-Learner
  • 523
  • 5
  • 18
exd5cxd4
  • 431
  • 4
  • 5
6

If you are doing this in a browser, you can capture keyboard events.

  • keydown
  • keypress
  • keyup

Can all be listened to on HTML nodes in most browsers.

Webkit also supports...

  • textInput

See for more details .. http://unixpapa.com/js/key.html

ocodo
  • 29,401
  • 18
  • 105
  • 117
4

Since event.keyCode is deprecated, I found the event.key useful in javascript. Below is an example for getting the names of the keyboard keys pressed (using an input element). They are given as a KeyboardEvent key text property:

function setMyKeyDownListener() {
    window.addEventListener(
      "keydown",
      function(event) {MyFunction(event.key)}
    )
}

function MyFunction (the_Key) {
    alert("Key pressed is: "+the_Key);
}
html { font-size: 4vw; background-color: green; color: white; padding: 1em; }
<body onload="setMyKeyDownListener()">
    <div>
        <input id="MyInputId">
    </div>
</body>
</html>
Nir Tsabar
  • 69
  • 1
  • 2
3

Use JQuery keydown event.

$(document).keypress(function(){
    if(event.which == 70){  //f
        console.log("You have payed respect");
    }
});

In JS; keyboard keys are identified by Javascript keycodes