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

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

  1. 1. kirtanya on June 17th, 2009 at 10:13 am

    i think it is great. i wish more and more people took to simplifying like you u do. good work Ganeshji!

  2. 2. kurotsuto on June 26th, 2009 at 7:19 pm

    Simply spectacular. 195 bytes?!?!?! AMAZING.

  3. 3. dobi on July 2nd, 2009 at 12:05 pm

    hi~ It is so great.

    When I tested this code in Chrome, work well.

    But when I tried this in IE, there was some error that I didn’t know.
    So didn’t work…

    Please test in IE, and let me know how to resolve this problem.

  4. 4. Dobi on July 2nd, 2009 at 12:06 pm

    %ps – Version of IE is 8.

  5. 5. Ganeshji Marwaha on July 2nd, 2009 at 6:08 pm

    @Dobi #3, #4: You are right. There was an error in IE. IE throws an error when your callback function doesn’t have any args. I have FIXED the code and updated it in the blog entry. Kindly take the latest code from the blog entry and check if it works for you. I checked it in IE 6 and 7, but not in IE 8. So, kindly lemme know if it works for you.

  6. 6. A Nony Mouse on July 3rd, 2009 at 6:50 am

    In my experience e.ctrlKey is true if the control key is down, not just if it is the key that was pressed. You could remove isCtrl and replace it with e.ctrlKey. Also watch out, some browsers (at least IE and chrome) will send back different character code for the enter key if ctrl is held down. not a problem if you are just using it for CTRL-S

  7. 7. Ganeshji Marwaha on July 4th, 2009 at 4:05 pm

    @A Nony Mouse #6: Thanks for your input. I have updated the plugin based on your input. It does make the plugin look a lot cleaner and now it is a lot smaller.

  8. 8. remzi on August 10th, 2009 at 5:24 pm

    thanks so much

  9. 9. dk4r on September 11th, 2009 at 3:24 am

    When I use this plug in in FF, I press Ctrl + S, FF show me the Save dialog, how can I disable it, mean when I click Ctrl + S, my page save content, It doesn’t fire the FF save dialog. Like gmail, if I’m focus on textbox, press Ctrl+S, it shows me Saving…, if I leave the textbox and press Ctrl+S again, it shows me the FF Save Dialog. Thank you and waiting for your reply.

  10. 10. travesti on November 15th, 2009 at 2:54 am

    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.

  11. 11. Jordan Boesch on January 7th, 2010 at 1:58 am

    Cool plugin! I wrote something pretty similar recently that adds a new event that you can bind called “keystrokes”. Check it out!
    http://boedesign.com/blog/2009/12/30/keystrokes-for-jquery/

  12. 12. krishna on February 10th, 2010 at 5:47 am

    Hi this is krishna i need help from you when i am calling javascript function Ctrl+D event has to be fire can you please give me solution pleeeez

  13. 13. David S on February 17th, 2010 at 8:09 pm

    This worked great, although I did need to tweak it slightly as I needed to modify Ctrl+Insert, which required a keycode.

    This is how I modified the code:

    $.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;
    var kc = parseInt(key);
    if((!isNaN(kc) && kc > 0 && e.keyCode == key || isNaN(kc) && e.keyCode == key.charCodeAt(0)) && isCtrl) {
    callback.apply(this, args);
    return false;
    }
    }).keyup(function(e) {
    if(e.ctrlKey) isCtrl = false;
    });
    };

    $.ctrl(45, function() { alert(‘custom functionality goes here’); return false; });

  14. 14. Tony on February 19th, 2010 at 12:51 am

    Hi, is there a way to invoke the Ctrl+F key combo from a simple hyperlink using jquery, to bring up the “find in page” box in all browsers?

  15. 15. syava on March 30th, 2010 at 4:00 pm

    [...] you … 759. syava on February 17th, 2010 at 3:26 pm. Script has some bugs with content that …Ctrl + Key Combination Simple Jquery Plugin | GaneshIn a recent web application I was working on, I had a need for the Ctrl + S hotkey to save an entry [...]

  16. 16. travesti on April 25th, 2010 at 10:19 am

    Ctrl” key is down even if another key is being pressed along with Ctrl.

  17. 17. travesti on May 30th, 2010 at 8:49 am

    Ctrl” key is down even if another key is being pressed along with gallr

  18. 18. bolu on June 1st, 2010 at 6:34 pm

    thank admin

  19. 19. Cindy on July 14th, 2010 at 8:56 am

    Thanks

Leave a Reply