There are many questions that refer to keyCode
(deprecated) and code
, but I am not seeing much in regards to key
. I am trying to reduce the amount of “magic strings” in my code.
Should I be using key
, or should I switch to code
? The code
does not know if the Shift key was hit, but the key
will be formatted in upper-case. Key also works with special characters, because it detects the keyboard layout better.
I am using the following logic, but I do not want to potentially create a map of all keys if I can help it.
const VirtualKeyBoard = {
ENTER: 'Enter',
A_LOWER: 'a',
A_UPPER: 'A',
}
const elements = {
code : document.querySelector('#code'),
key : document.querySelector('#key'),
keyCode : document.querySelector('#keyCode'),
};
const updateMap = (e) =>
Object.keys(elements).forEach((key) =>
elements[key].textContent = e[key]);
const onKeyPress = (e) => {
const { code, key, keyCode } = e;
updateMap(e);
if (key === VirtualKeyBoard.ENTER) {
console.log('You hit ENTER!');
} else if (key === VirtualKeyBoard.A_LOWER) {
console.log('You hit lower-case "a"!');
} else if (key === VirtualKeyBoard.A_UPPER) {
console.log('You hit upper-case "A"!');
}
}
document.body.addEventListener('keypress', onKeyPress);
.as-console-wrapper {
max-height: 4em !important;
}
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
body {
display: flex;
justify-content: center;
align-items: flex-start;
}
.grid {
display: grid;
grid-row-gap: 0.25em;
padding: 0.5em;
border: thin solid grey;
}
.grid-2 {
grid-template-columns: repeat(2, 1fr);
grid-column-gap: 1em;
}
<div class="grid grid-2">
<div>Code</div>
<div id="code">_</div>
<div>Key</div>
<div id="key">_</div>
<div>KeyCode</div>
<div id="keyCode">_</div>
</div>