--- title: KeyboardEvent.key slug: Web/API/KeyboardEvent/key translation_of: Web/API/KeyboardEvent/key ---

{{APIRef("DOM Events")}}

La propiedad de solo lectura KeyboardEvent.key retorna el valor de la tecla presionada por el usuario while taking into considerations the state of modifier keys such as the shiftKey as well as the keyboard locale/layout. Its value is determined as follows:

See a full list of key values.

KeyboardEvent Sequence

KeyboardEvents are fired in a pre-determined sequence and understanding this will go a long way into understanding the key property value for a particular KeyboardEvent. For a given key press, the sequence of KeyboardEvents fired is as follows assuming that {{domxref("Event.preventDefault")}} is not called:

  1. A {{event("keydown")}} event is first fired. If the key is held down further and the key produces a character key, then the event continues to be emitted in a platform implementation dependent interval and the {{domxref("KeyboardEvent.repeat")}} read only property  is set to true.
  2. If the key produces a character key that would result in a character being inserted into possibly an {{HTMLElement("input")}}, {{HTMLElement("textarea")}} or an element with {{domxref("HTMLElement.contentEditable")}} set to true, the {{event("beforeinput")}} and {{event("input")}} event types are fired in that order. Note that some other implementations may fire {{event("keypress")}} event if supported. The events will be fired repeatedly while the key is held down.
  3. A {{event("keyup")}} event is fired once the key is released. This completes the process.

In sequence 1 & 3, the KeyboardEvent.key attribute is defined and is set appropriately to a value according to the rules defined ealier.

KeyboardEvent Sequence Sample

Consider the event sequence generated when we interact with the ShiftKey and the legend key 2 using a U.S keyboard layout and a UK keyboard layout.

Try experimenting using the following two test cases:

  1. Press and hold the shift key, then press key 2 and release it. Next, release the shift key.
  2. Press and hold the shift key, then press and hold key 2. Release the shift key. Finally, release key 2.

HTML

<div class="fx">
  <div>
    <textarea rows="5" name="test-target" id="test-target"></textarea>
    <button type="button" name="btn-clear-console" id="btn-clear-console">clear console</button>
  </div>
  <div class="flex">
    <div id="console-log"></div>
  </div>
</div>

CSS

.fx {
  -webkit-display: flex;
  display: flex;
  margin-left: -20px;
  margin-right: -20px;
}

.fx > div {
  padding-left: 20px;
  padding-right: 20px;
}

.fx > div:first-child {
   width: 30%;
}

.flex {
  -webkit-flex: 1;
  flex: 1;
}

#test-target {
  display: block;
  width: 100%;
  margin-bottom: 10px;
}

JavaScript

let textarea = document.getElementById('test-target'),
consoleLog = document.getElementById('console-log'),
btnClearConsole = document.getElementById('btn-clear-console');

function logMessage(message) {
  let p = document.createElement('p');
  p.appendChild(document.createTextNode(message));
  consoleLog.appendChild(p);
}

textarea.addEventListener('keydown', (e) => {
  if (!e.repeat)
    logMessage(`first keydown event. key property value is "${e.key}"`);
  else
    logMessage(`keydown event repeats. key property value is "${e.key}"`);
});

textarea.addEventListener('beforeinput', (e) => {
  logMessage(`beforeinput event. you are about inputing "${e.data}"`);
});

textarea.addEventListener('input', (e) => {
  logMessage(`input event. you have just inputed "${e.data}"`);
});

textarea.addEventListener('keyup', (e) => {
  logMessage(`keyup event. key property value is "${e.key}"`);
});

btnClearConsole.addEventListener('click', (e) => {
  let child = consoleLog.firstChild;
  while (child) {
   consoleLog.removeChild(child);
   child = consoleLog.firstChild;
  }
});

Result

{{EmbedLiveSample('KeyboardEvent_Sequence_Sample')}}

Case 1

When the shift key is pressed, a {{event("keydown")}} event is first fired, and the key property value is set to the string "Shift". As we keep holding this key, the {{event("keydown")}} event does not continue to fire repeatedly because it does not produce a character key.

When key 2 is pressed, another {{event("keydown")}} event is fired for this new key press, and the key property value for the event is set to the string "@" for the U.S keyboard type and """ for the UK keyboard type, because of the active modifier shift key. The {{event("beforeinput")}} and {{event("input")}} events are fired next because a character key has been produced.

As we release the key 2, a {{event("keyup")}} event is fired and the key property will maintain the string values "@" and """ for the different keyboard layouts respectively.

As we finally release the shift key, another {{event("keyup")}} event is fired for it, and the key attribute value remains "Shift".

Case 2

When the shift key is pressed, a {{event("keydown")}} event is first fired, and the key property value is set to be the string "Shift". As we keep holding this key, the keydown event does not continue to fire repeatedly because it produced no character key.

When key 2 is pressed, another {{event("keydown")}} event is fired for this new key press, and the key property value for the event is set to be the string "@" for the U.S keyboard type and """ for the UK keyboard type, because of the active modifier shift key. The {{event("beforeinput")}} and {{event("input")}} events are fired next because a character key has been produced. As we keep holding the key, the {{event("keydown")}} event continues to fire repeatedly and the {{domxref("KeyboardEvent.repeat")}}  property is set to true. The {{event("beforeinput")}} and {{event("input")}} events are fired repeatedly as well.

As we release the shift key, a {{event("keyup")}} event is fired for it, and the key attribute value remains "Shift". At this point, notice that the key property value for the repeating keydown event of the key 2 key press is now "2" because the modifier shift key is no longer active. The same goes for the {{domxref("InputEvent.data")}} property of the {{event("beforeinput")}} and {{event("input")}} events.

As we finally release the key 2, a {{event("keyup")}} event is fired but the key property will be set to the string value "2" for both keyboard layouts because the modifier shift key is no longer active.

Example

This example uses {{domxref("EventTarget.addEventListener()")}} to listen for {{event("keydown")}} events. When they occur,  the key's value is checked to see if it's one of the keys the code is interested in, and if it is, it gets processed in some way (possibly by steering a spacecraft, perhaps by changing the selected cell in a spreadsheet).

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

  switch (event.key) {
    case "Down": // IE specific value
    case "ArrowDown":
      // Do something for "down arrow" key press.
      break;
    case "Up": // IE specific value
    case "ArrowUp":
      // Do something for "up arrow" key press.
      break;
    case "Left": // IE specific value
    case "ArrowLeft":
      // Do something for "left arrow" key press.
      break;
    case "Right": // IE specific value
    case "ArrowRight":
      // Do something for "right arrow" key press.
      break;
    case "Enter":
      // Do something for "enter" or "return" key press.
      break;
    case "Escape":
      // Do something for "esc" 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);

Specification

Specification Status Comment
{{SpecName('DOM3 Events', '#widl-KeyboardEvent-key', 'KeyboardEvent.key')}} {{Spec2('DOM3 Events')}} Initial definition, included key values.

Browser compatibility

{{Compat("api.KeyboardEvent.key")}}