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

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

}); </script> </head>


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 for HERE Technologies. 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. You can even buy me a coffee!

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