Capture Shift, Alt and Ctrl Keys using jQuery

A user mailed me a question:

I have a Form. If a user clicks on a Button control or clicks anywhere in the form holding the Shift, Alt or Ctrl Keys, I want to capture these keys and take a different action.

Here’s how to achieve this simple task:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Capture Shift, Alt and Ctrl Keys</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(document).click(function(e) {
if (e.shiftKey) {
alert("Shift pressed");
}
else if (e.ctrlKey) {
alert("Ctrl Pressed");
}
else if (e.altKey) {
alert("Alt Pressed");
}
});
</script>
</
head>
<
body>

</
body>
</
html>


image






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: