jQuery Quickie - Noticing ctrl/shift keyboard events

This post is more than 2 years old.

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:

<html>

<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&lt;br/&gt;";
		else s += "CTRL OFF&lt;br/&gt;";

		if (e.shiftKey) s += "SHIFT ON&lt;br/&gt;";
		else s += "SHIFT OFF&lt;br/&gt;";

		s+= "Key : " + e.which;
		$("#test").html(s);		 
		e.preventDefault();
	});

}); </script> </head>

<body>

Type on your keyboard... <p/>

<div id="test"></div>

</body> </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.

Raymond Camden's Picture

About Raymond Camden

Raymond is a senior developer evangelist for Adobe. He focuses on document services, JavaScript, and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Archived Comments

Comment 1 by Phillip Senn posted on 8/23/2011 at 10:48 PM

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;

Comment 2 by Will B. posted on 8/23/2011 at 11:15 PM

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.)

Comment 3 by Raymond Camden posted on 8/23/2011 at 11:22 PM

I didn't try keyup. Quick demo - what can I say? ;)

Comment 4 by Andy Sandefer posted on 8/24/2011 at 4:23 AM

Thanks for the help Ray!