- KeyboardEvent.key
- Key values
- KeyboardEvent sequence
- KeyboardEvent sequence example
- HTML
- CSS
- JavaScript
- Result
- Case 1
- Case 2
- Example
- Specification
- Browser compatibility
- Found a content problem with this page?
- JavaScript detecting which key is pressed
- Detecting keys in JavaScript permalink
- HTML Structure permalink
- Assigning the keypress to our front-end permalink
- Thank you for reading, and let’s connect! permalink
KeyboardEvent.key
Ключ события KeyboardEvent key доступен только для чтения, возвращает значение клавиши, нажатой пользователем, принимая во внимание состояние клавиш-модификаторов, таких как Shift , а также локаль и раскладку клавиатуры. Его значение определяется следующим образом:
Key values
- If the pressed key has a printed representation, the returned value is a non-empty Unicode character string containing the printable representation of the key.
- If the pressed key is a control or special character, the returned value is one of the pre-defined key values.
- If the KeyboardEvent represents the press of a dead key, the key value must be » Dead «.
- Some specialty keyboard keys (such as the extended keys for controlling media on multimedia keyboards) don’t generate key codes on Windows; instead, they trigger WM_APPCOMMAND events. These events get mapped to DOM keyboard events, and are listed among the «Virtual key codes» for Windows, even though they aren’t actually key codes.
- If the key cannot be identified, the returned value is «Unidentified» .
KeyboardEvent sequence
Every KeyboardEvent is fired in a pre-determined sequence. For a given key press, the sequence of KeyboardEvent s fired is as follows assuming that Event.preventDefault is not called:
- A keydown (en-US) 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 KeyboardEvent.repeat (en-US) read only property is set to true .
- If the key produces a character key that would result in a character being inserted into possibly an , (en-US) or an element with HTMLElement.contentEditable set to true, the beforeinput and input (en-US) event types are fired in that order. Note that some other implementations may fire keypress (en-US) event if supported. The events will be fired repeatedly while the key is held down.
- A keyup (en-US) 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 example
Consider the event sequence generated when we interact with the Shift and the 2 key using a U.S keyboard layout as compared to when we do so using a UK keyboard layout.
Try experimenting using the following two test cases:
- Press and hold the Shift key, then press 2 and release it. Next, release the Shift key.
- Press and hold the Shift key, then press and hold 2 . Release the Shift key. Finally, release 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 consolebutton> div> div class="flex"> pre 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) document.getElementById("console-log").innerHTML += message + "
"; > textarea.addEventListener('keydown', (e) => if (!e.repeat) logMessage(`Key "$e.key>" pressed [event: keydown]`); else logMessage(`Key "$e.key>" repeating [event: keydown]`); >); textarea.addEventListener('beforeinput', (e) => logMessage(`Key "$e.data>" about to be input [event: beforeinput]`); >); textarea.addEventListener('input', (e) => logMessage(`Key "$e.data>" input [event: input]`); >); textarea.addEventListener('keyup', (e) => logMessage(`Key "$e.key>" released [event: keyup]`); >); btnClearConsole.addEventListener('click', (e) => let child = consoleLog.firstChild; while (child) consoleLog.removeChild(child); child = consoleLog.firstChild; > >);
Result
Примечание: On browsers that don’t fully implement the InputEvent interface which is used for the beforeinput and input (en-US) events, you may get incorrect output on those lines of the log output.
Case 1
When the shift key is pressed, a keydown (en-US) event is first fired, and the key property value is set to the string «Shift» . As we keep holding this key, the keydown (en-US) event does not continue to fire repeatedly because it does not produce a character key.
When key 2 is pressed, another keydown (en-US) 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 beforeinput and input (en-US) events are fired next because a character key has been produced.
As we release the key 2 , a keyup (en-US) 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 keyup (en-US) event is fired for it, and the key attribute value remains «Shift» .
Case 2
When the shift key is pressed, a keydown (en-US) 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 keydown (en-US) 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 beforeinput and input (en-US) events are fired next because a character key has been produced. As we keep holding the key, the keydown (en-US) event continues to fire repeatedly and the KeyboardEvent.repeat (en-US) property is set to true . The beforeinput and input (en-US) events are fired repeatedly as well.
As we release the shift key, a keyup (en-US) 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 InputEvent.data (en-US) property of the beforeinput and input (en-US) events.
As we finally release the key 2 , a keyup (en-US) 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 EventTarget.addEventListener() to listen for keydown (en-US) 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).
.addEventListener("keydown", function (event) if (event.defaultPrevented) return; // Do nothing if the event was already processed > switch (event.key) case "Down": // IE/Edge specific value case "ArrowDown": // Do something for "down arrow" key press. break; case "Up": // IE/Edge specific value case "ArrowUp": // Do something for "up arrow" key press. break; case "Left": // IE/Edge specific value case "ArrowLeft": // Do something for "left arrow" key press. break; case "Right": // IE/Edge specific value case "ArrowRight": // Do something for "right arrow" key press. break; case "Enter": // Do something for "enter" or "return" key press. break; case "Esc": // IE/Edge specific value 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 |
---|---|---|
Document Object Model (DOM) Level 3 Events Specification Определение ‘KeyboardEvent.key’ в этой спецификации. | Устаревшая | Initial definition, included key values. |
UI Events Определение ‘KeyboardEvent.key’ в этой спецификации. | Рабочий черновик |
Browser compatibility
BCD tables only load in the browser
Found a content problem with this page?
JavaScript detecting which key is pressed
You might find yourself in a situation where certain keypresses might do something for your application or game.
Today we’ll be looking at detecting which key is pressed in JavaScript.
The result is this cool little playground:
Detecting keys in JavaScript permalink
Let’s start with the basics. We will need a way for JavaScript to be aware any key is pressed.
document.onkeydown = function (e) console.log('key down'); console.log(e); >;
This will log all key-down events, which is what we are looking for.
The e variable will contain the actual KeyBoardEvent and has quite the information inside.
- key: A string representation of the key pressed
- keyCode: The number associated with the key. This is mainly used to identify keys in code
- code: A combination to identify which side a key was pressed (leftMeta/rightMeta)
Knowing that, let’s make an excellent visual tool that will output these three elements for the user.
HTML Structure permalink
I’m going to be using Tailwind to make a quick styled application. The main setup will be:
body class="mx-auto my-auto bg-gray-100"> div class="max-w-md px-8 py-4 my-20 bg-white rounded-lg shadow-lg"> div class="flex justify-center hidden -mt-16"> div class="flex items-center justify-center object-cover w-20 h-20 text-3xl bg-white border-2 border-indigo-500 rounded-full" id="keyCodeLarge" >div> div> div> p class="text-gray-600" id="info">Press any key to see the magic 🪄p> p class="hidden mt-4 text-gray-600">key: span id="key">span>p> p class="hidden mt-2 text-gray-600">code: span id="code">span>p> p class="hidden mt-2 text-gray-600"> keyCode: span id="keyCode">span> p> div> div> body>
As you might have noted, I’ve added some ids based on which we will add the represented value with JavaScript.
I’ve also added an information paragraph for when we don’t have any keypress yet.
Assigning the keypress to our front-end permalink
We start by defining the variables we are going to be needing.
const key = document.getElementById('key'), code = document.getElementById('code'), keyCode = document.getElementById('keyCode'), keyCodeLarge = document.getElementById('keyCodeLarge'), info = document.getElementById('info'), hiddenElements = document.querySelectorAll('.hidden');
This mixes the key information we will place and the hidden fields we need to show.
Now in our keyDown function, we can act on this and place the right information.
document.onkeydown = function (e) [].forEach.call(hiddenElements, function (el) el.classList.remove('hidden'); >); info.classList.add('hidden'); key.innerHTML = e.key; code.innerHTML = e.code; keyCode.innerHTML = e.keyCode; keyCodeLarge.innerHTML = e.keyCode; >;
That is as simple as it gets!
You can try it out in this Codepen.
Thank you for reading, and let’s connect! permalink
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter