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 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 focus
so are likely to be targeted. Press a key in the input element below.
<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. Press and hold a key in the input element below.
<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. Press and release a key in the input element below.
<script type="text/javascript">
var a = 0;
$("input").keyup(function(){
$("span").text(++a)
});
</script>
Did you find the page informational and useful? Share it using one of your favorite social sites.
Recommended Books & Training Resources