Contents:
.on( "keydown" [, eventData ], handler )Returns: jQuery
Description: Bind an event handler to the "keydown" event.
-
version added: 1.7.on( "keydown" [, eventData ], handler )
This page describes the keydown
event. For the deprecated .keydown()
method, see .keydown()
.
The keydown
event is sent to an element when the user presses a key on the keyboard. If the key is kept pressed, the event is sent every time the operating system repeats the key. It 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 elements can always get focus so are reasonable candidates for this event type.
For example, consider the HTML:
1
2
3
4
5
6
|
|
The event handler can be bound to the input field:
1
2
3
|
|
Now when the insertion point is inside the field, pressing a key displays the alert:
Handler for `keydown` called.
To trigger the event manually, use .trigger( "keydown" )
:
1
2
3
|
|
After this code executes, clicks on Trigger the handler will also alert 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 key was pressed, 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 key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows. For catching actual text entry, .keypress()
may be a better choice.
Example:
Show the event object for the keydown handler when a key is pressed in the input.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
|
Demo:
.trigger( "keydown" )Returns: jQuery
Description: Trigger the "keydown" event on an element.
-
version added: 1.0.trigger( "keydown" )
-
"keydown"Type: stringThe string
"keydown"
.
-
See the description for .on( "keydown", ... )
.