Ctrl + Key Combination – Simple Jquery Plugin June 16th, 2009

In a recent web application I was working on, I had a need for the “Ctrl + S” hotkey to save an entry to the database. Being a an avid jquery fan, I immediately searched the plugin repository for any plugin that fits the bill. I was not very surprised to find a very comprehensive jshotkeys plugin. It was feature rich and addressed all the requirements for hotkeys in a jquery powered application and obviously my requirement was fulfilled as well.

But the basic issue (and advantage too) with any plugin is that it is written for a wide range of audience. So, although my requirement was only for a “Ctrl + key” combination, I had to part with my bandwidth for all other features this plugin offered. Like my famous jCarouselLite plugin, I like my javascript code kept to the minimum. So, I decided and wrote a short yet sweet plugin that would solve only the problem I have at hand. Unsurprisingly, the plugin code turned out to be only 195 bytes (minified). Given below is the code for the same…

$.ctrl = function(key, callback, args) {
    var isCtrl = false;
    $(document).keydown(function(e) {
        if(!args) args=[]; // IE barks when args is null
        
        if(e.ctrlKey) isCtrl = true;
        if(e.keyCode == key.charCodeAt(0) && isCtrl) {
            callback.apply(this, args);
            return false;
        }
    }).keyup(function(e) {
        if(e.ctrlKey) isCtrl = false;
    });        
};

This is how it works:

1. You want to execute a function when the user presses a “Ctrl + key” combination.
2. You as a developer should call the plugin method and pass in 3 parameters.
3. 1st Param: The “key” user should press while he is pressing Ctrl.
4. 2nd Param: The callback function to be executed when the user presses “Ctrl + key”.
5. 3rd Param: An optional array of arguments, that will be passed to the callback function.

In the code given below, when the user presses the “Ctrl + S” key combination, the anonymous callback function passed in as the second parameter is called.

$.ctrl('S', function() {
    alert("Saved");
});

Here, when the user presses the “Ctrl + S” key combination, the anonymous callback function passed in as the second parameter is called with the arguments passed in as the third parameter.

$.ctrl('D', function(s) {
    alert(s);
}, ["Control D pressed"]);

Thats it. I feel it is simple yet effective and solves a common requirement in modern web applications.

What do you think?

Update

A comment provided by “A Nony Mouse” in this blog entry clarified that, we don’t have to store a boolean called “isCtrl” to check if the “Ctrl” key is down while another key is being pressed. It is enough to check for e.ctrlKey as it will return true if the “Ctrl” key is down even if another key is being pressed along with Ctrl. Based on that input the “Ctrl + Key” plugin has been updated. Take a look at the updated code below. For archiving purposes, I am leaving the original version of the code above without any changes.

$.ctrl = function(key, callback, args) {
    $(document).keydown(function(e) {
        if(!args) args=[]; // IE barks when args is null 
        if(e.keyCode == key.charCodeAt(0) && e.ctrlKey) {
            callback.apply(this, args);
            return false;
        }
    });        
};

65 Responses to “Ctrl + Key Combination – Simple Jquery Plugin”

« 1 2 Show All

  1. 51. hardwood stairs on December 21st, 2011 at 5:01 pm

    To add onto the funeral I described previously. I just tested it with jQuery 1.4.3 and it’s deed the same thing.

  2. 52. jQuery tips and plugins by chris.stahl - Pearltrees on January 9th, 2012 at 12:21 am

    [...] Ctrl + Key Combination – Simple Jquery Plugin | Ganesh [...]

  3. 53. Javascript by biible - Pearltrees on January 9th, 2012 at 12:21 am

    [...] Ctrl + Key Combination – Simple Jquery Plugin | Ganesh But the basic issue (and advantage too) with any plugin is that it is written for a wide range of audience. So, although my requirement was only for a “Ctrl + key” combination, I had to part with my bandwidth for all other features this plugin offered. Like my famous jCarouselLite plugin, I like my javascript code kept to the minimum. So, I decided and wrote a short yet sweet plugin that would solve only the problem I have at hand. Unsurprisingly, the plugin code turned out to be only 195 bytes (minified). Given below is the code for the same… [...]

  4. 54. johnies on January 18th, 2012 at 9:54 pm

    Thanks a lot for the plugin. I had some issues though. While the event is captured every time the user presses the combination, sometimes (not sure when) the default behavior of the browser is not prevented. So i added e.preventDefault(); right before return false; and it works every time!!

  5. 55. Adam on February 20th, 2012 at 10:55 pm

    How do I make this work with the Cmd key on a mac?

  6. 56. LEOG on February 27th, 2012 at 5:50 pm

    Hi,

    Great Code!!

    I tried to use the code when I click ‘Ctrl + A’ and it works fine!!,

    However, when I use the same ‘Ctrl + A’ over an iFrame it doesn’t works.
    Do you know why?

    Note: Of course both, iframe and home page, are in the same Domain.

    Thank you.

  7. 57. Krishna on March 4th, 2012 at 3:04 pm

    Hi,

    I have a workflow of several pages. The Ctrl + S needs to fire different save methods in each page. How can I remove the assocation of previous page function. for e.g in page 1, i have registered $.ctrl(‘S’, function () { function1(); }); In page 2, I have registered $.ctrl(‘S’, function () { function2(); }); Now Ctrl + S in page 2 fires both the functions. How can I remove the call to the first function?

  8. [...] always wanted this functionality, and thanks to this guy, I coded a plugin that allows you to login to WordPress from any place by simply pressing Ctrl + [...]

  9. 59. Ganesh button | Altarversion on April 19th, 2012 at 3:04 am

    [...] Ctrl + Key Combination – Simple Jquery Plugin | GaneshJun 16, 2009 … In a recent web application I was working on, I had a need for the Ctrl + S hotkey to save an entry to the database. Being a an avid jquery fan, … [...]

  10. 60. Henjo on April 21st, 2012 at 11:58 pm

    In order to capture the cmd key as well, change ctrlKey to metaKey …

  11. 61. dj mixes on April 29th, 2012 at 11:34 pm

    actually very nice code, thanks for the tip, i am going to use it, i think!!

  12. 62. Anonymous on May 9th, 2012 at 9:08 pm

    @LEOG, an iframe is a different document so it isn’t going to work.

  13. 63. Jagadees on September 12th, 2012 at 7:31 am

    Ganesh,

    I tried with the above script. It worked fine in all browsers except “CTRL + T, CTRL + N” in chrome where New tab and New window opened though return false and e.preventDefault() method is provided. Also, I tried the same script for “ALT” where it worked in firefox and chrome but not in IE 8. Please let me know if I’m missing anything here to prevent the default browser function.

  14. 64. 14 Best Keyboard Plugins on October 3rd, 2012 at 11:35 am

    [...] Simple jQuery Plugin. Source + Demo [...]

  15. 65. Asaf Key on October 24th, 2012 at 10:32 am

    works like a charm. thanks!

« 1 2 Show All