John Magnolia
John Magnolia

Reputation: 16803

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.

Upvotes: 15

Views: 13785

Answers (4)

Zach Saucier
Zach Saucier

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

Michael_Scharf
Michael_Scharf

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

spyke
spyke

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

Barlas Apaydin
Barlas Apaydin

Reputation: 7315

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)

Upvotes: 4

Related Questions