Java Reference
In-Depth Information
The
String.fromCharCode()
method can then be used to convert the
event.charCode
property into a single-character string representation of the character
that will appear on the screen.
This all means that if you want to know which
key
was pressed, you should use the
key-
down
event and
event.keyCode
property. If you want to know which
character
will
be displayed, you should use the
keypress
event and the
event.keyChar
property.
Add the code to see an alert dialog showing which character was pressed:
addEventListener("keypress", function (event){
console.log("You pressed the " + String.fromCharCode
↵
(event.charCode) + " character");
});
Now when you press a key, you should see a message similar to this in the console:
"You pressed the J character"
"You stopped pressing the key at Wed Aug 20 2014 15:46:42
GMT+0100
↵
(BST)"
Modifier Keys
Pressing the modifier keys such as
Shift
,
Ctrl
,
Alt
, and
meta
(
Cmd
on Mac) will fire the
keydown
and
keyup
events, but not the
keypress
event as they don't produce any
characters on the screen.
The event object also contains information about whether a modifier key was held down
when the key event occurred. The
event.shiftKey
,
event.ctrlKey
,
event.altKey
, and
event.metaKey
are all properties of the event object and return
true
if the relevant key is held down when the event occurred. For example, the following
code will check to see if the user has pressed the
C
key (which has a keycode of 32) while
holding down the
Ctrl
key:
