Text Events
Browsers have three legacy events for keyboard input. The keydown and keyup events are low-level events that are covered in the next section. The keypress event, however, is a higher-level event that signals that a printable character has been generated. The DOM Level 3 Events draft specification defines a more general textinput event triggered whenever the user inputs text regardless of the source (a keyboard, data transfer in the form of a paste or a drop, an Asian-language input method, or a voice or handwriting recognition system, for example). The textinput event is not supported at the time of this writing, but Webkit browsers support a very similar “textInput” (with a capital letter I) event.
The proposed textinput event and the currently implemented
textInput event are passed a simple event object with a data
property that holds the input text.
(Another property, inputMethod
, is
proposed to specify the source of the input, but it has not yet been
implemented.) For keyboard input, the data
property will usually hold only a
single character, but input from other sources may often include
multiple characters.
The event object passed with keypress events is more confusing.
A keypress event represents a single character of input. The event
object specifies that character as a numeric Unicode codepoint, and
you must use String.fromCharCode()
to convert it to a string. In most browsers, the keyCode
property of the event object specifies the codepoint of the input character. ...
Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.