Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery keypress event for cmd+s AND ctrl+s

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.

like image 616
John Magnolia Avatar asked Jul 16 '12 10:07

John Magnolia


2 Answers

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;
});
like image 194
spyke Avatar answered Oct 14 '22 19:10

spyke


For detecting ctrl+s and cmd+s, you can use this way:

Working jsFiddle.

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)

like image 45
Barlas Apaydin Avatar answered Oct 14 '22 20:10

Barlas Apaydin