.keypress( handler(eventObject) )Returns: jQuery
version added: 1.0.keypress( handler(eventObject) )
handler(eventObject)Type: Function()A function to execute each time the event is triggered.
version added: 1.4.3.keypress( [eventData ], handler(eventObject) )
version added: 1.0.keypress()
- This signature does not accept any arguments.
Note: as the
keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.
This method is a shortcut for
.on( "keypress", handler ) in the first two variations, and
.trigger( "keypress" ) in the third.
keypress event is sent to an element when the browser registers keyboard input. This is similar to the
keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger
keydown events but not
keypress events. Other differences between the two events may arise depending on platform and browser.
keypress event handler can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form controls can always get focus so are reasonable candidates for this event type.
For example, consider the HTML:
The event handler can be bound to the input field:
Now when the insertion point is inside the field, pressing a key displays the log:
Handler for .keypress() called.
To trigger the event manually, apply
.keypress() without an argument:
After this code executes, clicks on the Trigger the handler div will also log the message.
If key presses anywhere need to be caught (for example, to implement global shortcut keys on a page), it is useful to attach this behavior to the
document object. Because of event bubbling, all key presses will make their way up the DOM to the
document object unless explicitly stopped.
To determine which character was entered, examine the
event object that is passed to the handler function. While browsers use differing properties to store this information, jQuery normalizes the
.which property so you can reliably use it to retrieve the character code.
keyup provide a code indicating which key is pressed, while
keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by
keyup, but as 97 by
keypress. An uppercase "A" is reported as 65 by all events. Because of this distinction, when catching special keystrokes such as arrow keys,
.keyup() is a better choice.
Show the event object when a key is pressed in the input. Note: This demo relies on a simple $.print() plugin (http://api.jquery.com/resources/events.js) for the event object's output.