Search code examples
jquerykeypresskeydownjquery-events

keypress, ctrl+c (or some combo like that)


I'm trying to create shortcuts on the website I'm making. I know I can do it this way:

if(e.which == 17) isCtrl=true;
if(e.which == 83 && isCtrl == true) {
    alert('CTRL+S COMBO WAS PRESSED!')
    //run code for CTRL+S -- ie, save!
    e.preventDefault();
}

But the example below is easier and less code, but it's not a combo keypress event:

$(document).keypress("c",function() {
  alert("Just C was pressed..");
});

So I want to know if by using this second example, I could do something like:

$(document).keypress("ctrl+c",function() {
  alert("Ctrl+C was pressed!!");
});

is this possible? I've tried it and it didn't work, what am I doing wrong?


Solution

  • Another approach (no plugin needed) is to just use .ctrlKey property of the event object that gets passed in. It indicates if Ctrl was pressed at the time of the event, like this:

    $(document).keypress("c",function(e) {
      if(e.ctrlKey)
        alert("Ctrl+C was pressed!!");
    });