Did you find this useful?
Socialize it today.


jQuery Keyboard Events

Thursday, June 28, 2012

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)


ParameterDescription
functionSpecifies 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> 


Keydown event #0


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> 


Keypress event #0


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> 


Keyup event #0

Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

HTML CSS and JavaScript Editor Pro jQuery JavaScript and jQuery: The Missing Manual