Reputation: 16803
Using one of the examples from a previous question I have:
$(window).keypress(function(event) {
if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
$("form input[name=save]").click();
event.preventDefault();
return false;
});
Is it also possible to change this to work for the Mac cmd key?
I have tried (!(event.which == 115 && (event.cmdKey || event.ctrlKey)) && !(event.which == 19))
but this didn't work.
Upvotes: 15
Views: 13785
Reputation: 25974
keydown
is the proper event to listen to as this is the one that most applications are hooked into (especially browsers).
Also, there's no reason to use jQuery for this these days. In modern JS:
document.addEventListener("keydown", (e) => {
if ((e.metaKey || e.ctrlKey) && e.key === "s") {
e.preventDefault();
// Do what you want here
}
});
Upvotes: 2
Reputation: 34548
This works for me:
$(document).keypress(function(event) {
if ((event.which == 115 || event.which == 83) && (event.ctrlKey||event.metaKey)|| (event.which == 19)) {
event.preventDefault();
// do stuff
return false;
}
return true;
});
Upvotes: 2
Reputation: 276
Use the event.metaKey to detect the Command key
$(document).keypress(function(event) {
if (event.which == 115 && (event.ctrlKey||event.metaKey)|| (event.which == 19)) {
event.preventDefault();
// do stuff
return false;
}
return true;
});
Upvotes: 26
Reputation: 7315
For detecting ctrl+s
and cmd+s
, you can use this way:
jQuery:
var isCtrl = false;
$(document).keyup(function (e) {
if(e.which == 17) isCtrl=false;
}).keydown(function (e) {
if(e.which == 17) isCtrl=true;
if(e.which == 83 && isCtrl == true) {
alert('you pressed ctrl+s');
return false;
}
});
source (includes all keyboard shorcuts and buttons)
Upvotes: 4