Unsere Freiwilligen haben diesen Artikel noch nicht in Deutsch übersetzt. Machen Sie mit und helfen Sie, das zu erledigen!
Sie können den Artikel auch auf English (US) lesen.

The KeyboardEvent.code property represents a physical key on the keyboard (as opposed to the character generated by pressing the key). In other words, this property returns a value which isn't altered by keyboard layout or the state of the modifier keys.

If the input device isn't a physical keyboard, but is instead a virtual keyboard or accessibility device, the returned value will be set by the browser to match as closely as possible to what would happen with a physical keyboard, to maximize compatibility between physical and virtual input devices.

This property is useful when you want to handle keys based on their physical positions on the input device rather than the characters associated with those keys; this is especially common when writing code to handle input for games which simulate a gamepad-like environment using keys on the keyboard. Be aware, however, that you can't use the value reported by KeyboardEvent.code to determine the character generated by the keystroke, because the keycode's name may not match the actual character that's printed on the key or that's generated by the computer when the key is pressed.

For example, the code returned is "KeyQ" for the "q" key on a QWERTY layout keyboard, but the same code value also represents the "'" key on Dvorak keyboards and the "a" key on AZERTY keyboards. That makes it impossible to use the value of code to determine what the name of the key is to users if they're not using an anticipated keyboard layout.

To determine what character corresponds with the key event, use the KeyboardEvent.key property instead.

Code values

The code values for Windows, Linux, and macOS are list on the KeyboardEvent: code values page.


Exercising KeyboardEvent


<p>Press keys on the keyboard to see what the KeyboardEvent's key and code
   values are for each one.</p>
<div id="output">


#output {
  font-family: Arial, Helvetica, sans-serif;
  border: 1px solid black;


window.addEventListener("keydown", function(event) {
  let str = "KeyboardEvent: key='" + event.key + "' | code='" +
            event.code + "'";
  let el = document.createElement("span");
  el.innerHTML = str + "<br/>";
}, true);

Try it out

To ensure that keystrokes go to the sample, click in the output box below before pressing keys.

Handle keyboard events in a game

This example establishes an event listener for keydown events which handles keyboard input for a game which uses the typical "WASD" keyboard layout for steering forward, left, backward, and right. This will use the same four keys physically regardless of what the actual corresponding characters are, such as if the user is using an AZERTY keyboard.


<p>Use the WASD (ZQSD on AZERTY) keys to move and steer.</p>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="world">
  <polygon id="spaceship" points="15,0 0,30 30,30"/>


.world {
  margin: 0px;
  padding: 0px;
  background-color: black;
  width: 400px;
  height: 400px;

#spaceship {
  fill: orange;
  stroke: red;
  stroke-width: 2px;


The first section of the JavaScript code establishes some variables we'll be using. shipSize contains the size of the ship the player is moving around, for convenience. position is used to track the position of the ship within the play field. moveRate and turnRate are the number of pixels forward and backward each keystroke moves the ship and how many degrees of rotation the left and right steering controls apply per keystroke. angle is the current amount of rotation applied to the ship, in degrees; it starts at 0° (pointing straight up). Finally, spaceship is set to refer to the element with the ID "spaceship", which is the SVG polygon representing the ship the player controls.

let shipSize = {
  width: 30,
  height: 30

let position = {
  x: 200,
  y: 200

let moveRate = 9;
let turnRate = 5;

let angle = 0;

let spaceship = document.getElementById("spaceship");

Next comes the function updatePosition(). This function takes as input the distance the ship is to be moved, where positive is a forward movement and negative is a backward movement. This function computes the new position of the ship given the distance moved and the current direction the ship is facing. It also handles ensuring that the ship wraps across the boundaries of the play field instead of vanishing.

function updatePosition(offset) {
  let rad = angle * (Math.PI/180);
  position.x += (Math.sin(rad) * offset);
  position.y -= (Math.cos(rad) * offset);
  if (position.x < 0) {
    position.x = 399;
  } else if (position.x > 399) {
    position.x = 0;
  if (position.y < 0) {
    position.y = 399;
  } else if (position.y > 399) {
    position.y = 0;

The refresh() function handles applying the rotation and position by using an SVG transform.

function refresh() {
  let x = position.x - (shipSize.width/2);
  let y = position.y - (shipSize.height/2);
  let transform = "translate(" + x + " " + y + ") rotate(" + angle + " 15 15) ";

  spaceship.setAttribute("transform", transform);

Finally, the addEventListener() method is used to start listening for keydown events, acting on each key by updating the ship position and rotation angle, then calling refresh() to draw the ship at its new position and angle.

window.addEventListener("keydown", function(event) {
  if (event.defaultPrevented) {
    return; // Do nothing if event already handled
  switch(event.code) {
    case "KeyS":
    case "ArrowDown":
      // Handle "back"
    case "KeyW":
    case "ArrowUp":
      // Handle "forward"
    case "KeyA":
    case "ArrowLeft":
      // Handle "turn left"
      angle -= turnRate;
    case "KeyD":
    case "ArrowRight":
      // Handle "turn right"
      angle += turnRate;
  // Consume the event so it doesn't get handled twice
}, true);

Try it out

To ensure that keystrokes go to the sample code, click inside the black game play field below before pressing keys.

There are several ways this code can be made better. Most real games would watch for keydown events, start motion when that happens, and stop the motion when the corresponding keyup occurs, instead of relying on key repeats. That would allow both smoother and faster movement, but would also allow the player to be moving and steering at the same time. Transitions or animations could be used to make the ship's movement smoother, too.


Specification Status Comment
UI Events
The definition of 'KeyboardEvent.code' in that specification.
Working Draft Initial definition, included code values.

Browser compatibility

Update compatibility data on GitHub
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
codeChrome Full support YesEdge No support NoFirefox Full support YesIE No support NoOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes


Full support  
Full support
No support  
No support

Schlagwörter des Dokuments und Mitwirkende

Zuletzt aktualisiert von: irenesmith,