jQuery supports a variety of keyboard related events. The three key related events are keydown, keypress and keyup. In this article, we will take a closer look at these events.
Syntax
$(selector).keydown(function) $(selector).keypress(function) $(selector).keyup(function)
HTML Example
We will use the following HTML for the examples listed below.
Keydown
The keydown event is triggered when the user first presses a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Elements that can have focus can vary between browsers.
However, form elements can always get focused so are likely to be targeted.
Keypress
The keypress event is similar to the keydown event, except in the case of key repeats. If the user presses and holds a key, a keydown event is triggered once, but separate keypress events are triggered for each inserted character.
Modifier keys (such as Shift, Alt, Ctrl) trigger keydown events but not keypress events.
Keyup
The keyup event is triggered when the user releases a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus.