![]() |
Question: How do I analyze keyboard events in JavaScript?
Answer:
When a user types a letter on the keyboard,
this usually triggers the keyboard events*
keydown
,
keypress
, and
keyup
(in this order).
To analyze keyboard events, your JavaScript code may use event-handler functions, which can access the event properties.
Some of these properties are the same across browsers (e.g. event.type
).
Other properties may be platform-dependent (e.g. event.which
is available in Firefox, Opera, Safari, Chrome,
but not in Internet Explorer).
Arguably, the most useful properties are event.which
, event.keyCode
, and
event.charCode
, because these properties allow your script to answer the questions:
keydown
event properties.)
keypress
event properties.)
Demo: Press or release any key on your keyboard, and the text boxes below will display the actual keyboard event properties available in your browser ():
Latest keydown:
Latest keypress:
Latest keyup:
*In addition to keydown
,
keypress
, and
keyup
, recent versions of Safari and Google Chrome support the textInput
event;
however, it is still too early to use textInput
in a cross-browser fashion.
Note also that some properties are event-specific
(e.g., in Safari and Chrome event.data
is available for textInput
events, but not for keydown
events).
Copyright © 1999-2011, JavaScripter.net.