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:
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With