A simple question: when I use the onkeydown
event in HTML, how can I find out what key was pressed? I'm sure it's really easy, but I've tried googling it; w3schools was no help, and all the other results were people asking about specific browsers. Is there no way which works in all major browsers?
Thanks!
The event you're looking for is the keydown Event, and it provides you with the following properties
char
DOMString (string) The character value of the key. If the key corresponds to a printable character, this value is a non-empty Unicode string containing that character. If the key doesn't have a printable representation, this is an empty string. See key names and char values for the detail. Read only.
Note: If the key is used as a macro that inserts multiple characters, this attribute's value is the entire string, not just the first character.
key
DOMString (string) The key value of the key represented by the event. If the value has a printed representation, this attribute's value is the same as the char attribute. Otherwise, it's one of the key value strings specified in {{ anch("Key values") }}. If the key can't be identified, this is the string "Unidentified". See key names and char values for the detail. Read Only.
charCode
Deprecated Unsigned long (int) The Unicode reference number of the key; this attribute is used only by the keypress event. For keys whose char attribute contains multiple characters, this is the Unicode value of the first character in that attribute. Read only.
Warning: This attribute is deprecated; you should use char instead, if available.
keyCode
Deprecated Unsigned long (int) A system and implementation dependent numerical code identifying the unmodified value of the pressed key. This is usually the decimal ASCII ({{ RFC(20) }}) or Windows 1252 code corresponding to the key; see {{ anch("Virtual key codes") }} for a list of common values. If the key can't be identified, this value is 0. Read only.
Warning: This attribute is deprecated; you should use key instead, if available.
which
Deprecated Unsigned long (int) A system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as keyCode. Read only.
Warning: This attribute is deprecated; you should use key instead, if available.
As implementation is inconsistant, you'll need to use a logical OR ||
to get the one supported by the client's browser.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With