In JavaScript, you can get the word definition of the key that was pressed, by looking at event.code
, such as:
document.onkeypress = function(event) {
console.log(event.code);
};
When I press a
, I get KeyA
. When I press the arrow up key, I get ArrowUp
. This is all fine for most keys, however, when I press a key like ½
on my keyboard with a Danish layout, I get Backquote
, which is not correct.
Instead of grabbing the hardcoded value that JavaScript gives me, I thought about converting event.key
instead, which returns the actual value of the keypress. For example, if I press SHIFT + 7 on my keyboard, event.key
will return /
which I want to be called slash
(or forward slash
).
Is there a way to convert a character to the actual word? I want an object/dictionary like this:
const keys = {
'/': 'forward slash', //or slash
'a': 'a',
'space': 'Space',
'"': 'Quotation mark',
'\'': 'Apostrophe'
};
and so on. Then I can do:
document.onkeypress = function(event) {
const characterPressed = keys[event.key];
console.log(characterPressed);
};
Is there a list I can iterate through to grab each value, or do I have to go through every character possible to be typed on a keyboard, and then map them manually? I'm basically looking for a "character to word definition" scheme.