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)
Parameter | Description |
---|---|
function | Specifies an optional function to run |
HTML Example
We will use the following HTML for the examples listed below.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// ... jQuery Code ...
});
</script>
</head>
<body>
<div id="div1"> <!-- Some Content --> </div>
</body>
</html>
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.
<script type="text/javascript">
var a = 0;
$("input").keydown(function(){
$("span").text(++a)
});
</script>
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.
<script type="text/javascript">
var a = 0;
$("input").keydown(function(){
$("span").text(++a)
});
</script>
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.
<script type="text/javascript">
var a = 0;
$("input").keyup(function(){
$("span").text(++a)
});
</script>