Find out which Key was pressed using jQuery

A user had a requirement to take actions on a page based on the KeyPressed. Here’s a simple script that you can do that and works cross-browser.

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>Find KeyPressed</title>

<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(document).ready(function() {
$(this).bind('keypress', function(e) {
var key = (e.keyCode ? e.keyCode : e.charCode);
alert(key);
});
});
</script>
</
head>
<
body>
<
div>
</
div>
</
body>
</
html>



You can also use ‘e.which’ instead of ‘e.charCode’. I have tested the code on IE7, Chrome and Firefox 3.

To do the same on an ASP.NET page, check my article over here Implementing KeyBoard Shortcuts in ASP.NET applications using jQuery



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: