Creating JavaScript Keyboard Shortcuts with jQuery

I recently added a keyboard shortcut to a project I was working on.

And while I have used the jQuery Hotkeys plugin for adding keyboard shortcuts recently, I didn’t use a plugin for this project since I only needed a single keyboard shortcut.

Taking a large bit of inspiration from Krasimir Tsonev, who also documented his solution, I came up with this:

[javascript]
(function( $ ) {
var $doc = $( document );
$doc.ready( function(){
$doc.on( ‘keydown’, function( e ){
if ( ! $( e.target ).is( ‘:input’ ) ) {

// props rauchg for pointing out e.shiftKey
if ( 87 == e.which && e.shiftKey ) {
// `shift` and `w` are pressed. Do something.
}
}
});
});

})( jQuery );
[/javascript]

Explanation

First, I create an anonymous function wrapper and invoke it while passing jQuery as a parameter. This allows me to use the $ syntax for jQuery without worrying about collisions with other libraries.

Then, after the DOM has loaded, I attach a keydown event handler to the document. Before I run any logic though, I check to make sure that we are currently not within any input type. This is important as I don’t want to trigger keyboard shortcuts when a user is typing.

After the code ensures that we are not in an input, I check to see if both the shift key and w have been pressed. If so, do some magic!

3 responses to “Creating JavaScript Keyboard Shortcuts with jQuery”

    1. Hey Guillermo, thanks for pointing that out! Code is much simpler with that little gem 🙂

  1. Cool stuff, thanks for sharing.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.