jQuery comes with three keyboard events to capture the keyboard activities – keyup(), keydown() and keypress().

  1. keyup() – Fire when user releases a key on the keyboard.
  2. keydown() – Fire when user presses a key on the keyboard.
  3. keypress() – Fire when user presses a key on the keyboard.

In general statement, the keydown() is similar to keypress() events. Actually there are quite few differential between keydown() and keypress() events.

1. Repeat keys

If you are press and hold a key, keydown() event is triggered once, but the keypress() event will keep triggering itself until you released the key.

2. Modifier keys

Keyboard modifier keys (ctrl, shift, alt…) will fire keydown() event but not keypress() event.

3. KeyCode – ASCII code

For example, A = 65 and a= 97, Please refer to this ASCII table charts.

  1. keydown() and keyup() will display a = 65, A = 65 (case insensitive – lowercase and uppercase will display same value).
  2. keypresss() will display a= 97, A=65 (case sensitive – lowercase and uppercase will display different value).

If you want to capture the real character key in, go for keypress() event.

KeyCode is not display in FireFox?

The event.keyCode is not working in FireFox , but work perfect in IE. To get the event.keyCode in Firefox, you should use the event.which instead, and jQuery recommend it as well. So the better way should be

var keycode = (event.keyCode ? event.keyCode : event.which);

Try it yourself

<html>
<head>
 
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
 
<style type="text/css">
	span{
		padding:8px;
		margin:8px;
		color:blue;
	}
	div{
		padding:8px;
		margin:8px;
	}
</style>
 
</head>
<body>
  <h1>jQuery keyup(), keydown() and keypress() example</h1>
 
<label>TextBox : </label>
<input id="textbox" type="text" size="50" />
 
<div>
<label>1. keyup() Message :</label> <span id="msg-keyup"></span>
</div>
 
<div>
<label>2. keydown() Message :</label><span id="msg-keydown"></span>
</div>
 
<div>
<label>3. keypress() Message :</label><span id="msg-keypress"></span>
</div>
 
<script type="text/javascript">
 
$('#textbox').keyup(function(event){
	$('#msg-keyup').html('keyup() is triggered!, keyCode = ' 
              + event.keyCode + ' which = ' + event.which)
});
 
$('#textbox').keydown(function(event){
	$('#msg-keydown').html('keydown() is triggered!, keyCode = ' 
              + event.keyCode + ' which = ' + event.which)
});
 
$('#textbox').keypress(function(event){
	$('#msg-keypress').html('keypress() is triggered!, keyCode = ' 
              + event.keyCode + ' which = ' + event.which)
});
 
</script>
</body>
</html>
Tags :
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

Related Posts

Popular Posts