Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print the name of a Key when it is Pressed?

Is it possible to get the name of a key when it is pressed:

field.addEventListener("keydown", keyDown, false);
function keyDown(event) {
    ...
}

For example when pressing the space key, I would like to get the string value: "space", or something along those lines. Is there an easy way to do this or do I require a library.

like image 714
user3024235 Avatar asked Dec 15 '22 05:12

user3024235


1 Answers

You can get the keycode, but not the name, because names vary across cultures, languages, etc., and JavaScript doesn't provide any means of getting the culture- and language-specific name appropriate to the current culture and language.

So the answer to "Is it possible to get the name of a key when it is pressed?" is: Not from anything built into JavaScript or the browser. You'll need lookup tables and/or a library. Beware that different keyboard layouts may give different mappings.

The keypress event gives you a character code for the matching character if there is one (on event.charCode, which you can use like String.fromCharCode(event.charCode)), but not keydown since not all keydowns generate characters (as distinct from other keypresses), and in fact sometimes it takes more than one keydown to create a character.


To get the keycode, just use:

var keyCode = event.which || event.keyCode || 0;

That will use event.which if it's present and truthy, or event.keyCode if it's present and truthy, or 0 if neither is present and truthy. Most browsers use which; many versions of IE use keyCode.

Since a key "name" would probably include modifiers, I'll mention that there are modifier flags available on the event as well: event.shiftKey, event.ctrlKey, event.altKey, and event.metaKey.

You'll see people telling you can use String.fromCharCode(keyCode) after doing the above to get a character for the key code. That's only true for a very small set of key codes, because key codes are not character codes. There is a small amount of overlap between the two, which is why people think you can do that. For instance, if you press a on your keyboard, on any keyboard I've ever heard of String.fromCharCode(keyCode) will give you "A" (and then you can use event.shiftKey to decide whether to make it lower case). But it falls down quickly when you get into anything beyond the 26 letters of the English alphabet (and probably the standard ten digits).

like image 52
T.J. Crowder Avatar answered Dec 29 '22 15:12

T.J. Crowder