Ctrl + Key Combination – Simple Jquery Plugin

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;
        }
    });        
};

Ganeshji Marwaha

I spend my days as the Director of Technology for Mobility practice and help my clients design enterprise and consumer mobile strategies. Mobile Payments, Digital Wallet and Tokenization technologies are my areas of specialization

65 Comments

  1. hardwood stairs   •  

    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. Pingback: jQuery tips and plugins by chris.stahl - Pearltrees

  3. Pingback: Javascript by biible - Pearltrees

  4. johnies   •  

    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. Adam   •  

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

  6. LEOG   •  

    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. Krishna   •  

    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. Pingback: aubreypwd — Aubrey Portwood: Web Developer & Designer based out of Scottsdale, Arizona.

  9. Pingback: Ganesh button | Altarversion

  10. Henjo   •  

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

  11. dj mixes   •  

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

  12. Anonymous   •  

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

  13. Jagadees   •  

    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. Pingback: 14 Best Keyboard Plugins

  15. Asaf Key   •  

    works like a charm. thanks!

Comments are closed.