Andy S. asked me earlier today...
I know how to trap for simple keyboard events using jQuery like so...
$(document).keydown(function (e){
if (e.which == 13){
doSomething();
}
});
How can I trap for keyboard combinations like someone pressing the Ctrl + Shift + F2 all at once?
I did some quick Googling and found this on the keydown() docs at jQuery.com:
You would check for event.shiftKey:
if ( event.which == 13 && event.shiftKey ) {
// do something
}
This was posted by Karl Swedberg. I took his idea and built up a simple demo:
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { $(document).keydown(function (e){
var s = '';
if (e.ctrlKey) s += "CTRL ON<br/>";
else s += "CTRL OFF<br/>"; if (e.shiftKey) s += "SHIFT ON<br/>";
else s += "SHIFT OFF<br/>"; s+= "Key : " + e.which;
$("#test").html(s);
e.preventDefault();
});
});
</script>
</head> <body> Type on your keyboard...
<p/> <div id="test"></div> </body>
</html>
<html>
As you can see, I look for both the ctrlKey and shiftKey flags in the event object. I create a string that shows what you typed along with whether or not the ctrl or shift (or both) keys were depressed. You can run this yourself using the link below. It worked fine in Chrome, Firefox, and, wait for it, yes, even Internet Explorer 9.
Archived Comments
This is better than other keyboard capturing routines that use variables to track special keys like:
if(myEvent.which == 16) isShift=true;
if(myEvent.which == 17) isCtrl =true;
if(myEvent.which == 18) isAlt = true;
I see you're capturing the shift ON and ctrl ON, but the page doesn't seem to show the OFF for either values unless you press another key (or shift or ctrl) again. Does that mean you can't detect the release of the key, or you just didn't happen to code it that way? (Chrome, here, by the way.)
I didn't try keyup. Quick demo - what can I say? ;)
Thanks for the help Ray!