23

I know that when keypress event occurs then we can access which key is pressed by object's event property keycode, but I need to know how do we can handle keypress combinations through jQuery like ctrl + D ..etc?

In the following code I tried to do something like :

$(document).on("keypress", function(e) { 
    if( /* what condition i can give here */ )           
        alert("you pressed cntrl + Del");
});
hamzeh.hanandeh
  • 733
  • 6
  • 21
Gaurav
  • 8,367
  • 14
  • 55
  • 90
  • 3
    look at this: http://stackoverflow.com/questions/10655202/detect-multiple-keys-on-single-keypress-event-on-jquery/10655316#10655316 On the side note...prefer my answer (hehe) – Parth Thakkar May 20 '12 at 08:09

2 Answers2

40

jQuery already handles this for you:

if ( e.ctrlKey && ( e.which === 46 ) ) {
  console.log( "You pressed CTRL + Del" );
}
Sampson
  • 265,109
  • 74
  • 539
  • 565
6

I know that this is an old question that has already been answered, but the answer marked as correct did not work for me. Here is a simple and easy method for catching the key combinations I wrote:

NOTE: This example is catching ctrl + space combination, but you can easily change it to any other keys.

    var ctrlPressed = false; //Variable to check if the the first button is pressed at this exact moment
    $(document).keydown(function(e) {
      if (e.ctrlKey) { //If it's ctrl key
        ctrlPressed = true; //Set variable to true
      }
    }).keyup(function(e) { //If user releases ctrl button
      if (e.ctrlKey) {
        ctrlPressed = false; //Set it to false
      }
    }); //This way you know if ctrl key is pressed. You can change e.ctrlKey to any other key code you want

    $(document).keydown(function(e) { //For any other keypress event
      if (e.which == 32) { //Checking if it's space button
        if(ctrlPressed == true){ //If it's space, check if ctrl key is also pressed
          myFunc(); //Do anything you want
          ctrlPressed = false; //Important! Set ctrlPressed variable to false. Otherwise the code will work everytime you press the space button again
        }
      }
    })
Vaxo Basilidze
  • 1,017
  • 13
  • 31