JQuery – Keyboard Input Events

In this souce code:
– Listen keyboard input event
– Example with jQuery if statement (dichiarazione)
– Cross Browser keyboard input events

NOTICE: 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.

The Source Code:

<!DOCTYPE html>
<html>
<!-- Don't Break My b***s - Gimme Code! Project                                              -->
<!-- Author: Andrea Tonin - http://blog.lucedigitale.com                                     -->
<!-- This code come with absolutely no warranty                                              -->
<!-- If you use this code in your project please give a link to http://blog.lucedigitale.com -->
<!-- Thanks in advance                                                                       -->
<head>
 
<script type="text/javascript" src="js/jquery-2.0.3.js"></script>
 
<style type="text/css">
	span{
		padding:8px;
		margin:8px;
		color:blue;
	}
	div{
		padding:8px;
		margin:8px;
	}
</style>
 
</head>
<body>
  <h1>jQuery Keyboard input Events</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>

<div>If you press ENTER a alert window appear.</div>
 
<script type="text/javascript">
 
/* Listen keyboard input event START */

/* NOTICE: 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 */ 

$('#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)
			  
			  /* Example with jQuery if statement (dichiarazione) */
			  if (event.keyCode == 13) { 
			  // Do whatever – enter key was pressed
			  alert('You press ENTER, the keycode is: ' + event.keyCode); 
			  }
});
 
$('#textbox').keypress(function(event){
	$('#msg-keypress').html('keypress() is triggered!, keyCode = ' 
              + event.keyCode + ' which = ' + event.which)
});
/* Listen keyboard input event END */  
</script>
</body>
</html>
DEMO

 

My official WebSite >