jQuery Quickie - Noticing ctrl/shift keyboard events

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

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 developer advocate looking for his next gig. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

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

Comments