Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery capture CTRL + S and Command + S (Mac)

I know this question was asked serval times here on stackoverflow and I tried some different solutions, but can't find a code that works for me.

I want to capture the keyboard command Ctrl+S and Command+S on Mac, currently I use this code (with jQuery 2.1.0):

jQuery(window).on('keypress', function(event){
    if (!(event.which == 115 && (event.ctrlKey||event.metaKey)) && !(event.which == 19)) return true;

    // my save function

    event.preventDefault();
    return false;
});

This Code works fine in:

  • Safari: With Ctrl+S and Command+S
  • Firefox: With Ctrl+S and Command+S
  • Chrome: Only Ctrl+S works

You will see that the problem is Google Chrome, here I can only capture Ctrl+S.

Has anybody an idea how I can solve this problem?

like image 244
Pascal Bajorat Avatar asked Dec 06 '22 03:12

Pascal Bajorat


1 Answers

This code works for me. I tested it in Chrome (v33) Firefox (v24) and Safari (v6.1.1 ). Both Control+S and Command+S work.

$(document).keydown(function(event) {
        // If Control or Command key is pressed and the S key is pressed
        // run save function. 83 is the key code for S.
        if((event.ctrlKey || event.metaKey) && event.which == 83) {
            // Save Function
            event.preventDefault();
            return false;
        };
    }
);

Please note that I am using keydown and not keypress. In the jQuery docs they sate:

Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.

I would avoid using it.

like image 72
bennick Avatar answered Dec 30 '22 14:12

bennick