Gaurav
Gaurav

Reputation: 8487

jQuery handling keypress combinations

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");
});

Upvotes: 24

Views: 20099

Answers (2)

Vaxo Basilidze
Vaxo Basilidze

Reputation: 1057

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
        }
      }
    })

Upvotes: 7

Sampson
Sampson

Reputation: 268344

jQuery already handles this for you:

if ( e.ctrlKey && ( e.which === 46 ) ) {
  console.log( "You pressed CTRL + Del" );
}

Upvotes: 41

Related Questions