event.keycode
In this chapter you will learn:
- How to get the keycode from event
- How to listen to the escape key
- How to use event.which to check the key code
- How to convert key code to char
Get the keycode
The following code gets the key code from event.
<html><!--from j av a 2s . c o m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(window).keydown(function(event){
alert(event.keyCode);
});
});
</script>
</head>
<body>
<body>
<p><input type="text" /> <span>focus event fire</span></p>
</body>
</html>
Escape key
To perform an action when the escape key has been released
<html><!--from j av a 2 s . c o m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).keyup(function(event){
if (event.keyCode == 27) {
alert('escaped!');
}
});
});
</script>
<style>
div.dbl { background:yellow;color:black; }
</style>
</head>
<body>
<body>
<p><input type="text" /> <span>focus fire</span></p>
<p><input type="password" /> <span>focus fire</span></p>
</body>
</html>
check key code
How to use event.which to check the key code.
<html><!--from j av a2 s . c om-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").keypress(function (e) {
if (e.which > 65 ) {
alert(e.which);
}
});
});
</script>
</head>
<body>
<body>
<input type="text" />
</body>
</html>
Convert key code to char
The following code converts key code to char in
keypress
event handler.
<html><!--from j a v a 2s . c o m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").keypress(function (e) {
var c = String.fromCharCode(e.which);
$("p").append($("<span/>")).children(":last").append(document.createTextNode(c));
$("div").text(e.which);
});
});
</script>
</head>
<body>
<body>
<input type="text" />
<p>Add text - </p>
<div></div>
</body>
</html>
Next chapter...
What you will learn in the next chapter: