Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery handling keypress combinations

Tags:

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"); }); 
like image 859
Gaurav Avatar asked May 20 '12 08:05

Gaurav


2 Answers

jQuery already handles this for you:

if ( e.ctrlKey && ( e.which === 46 ) ) {   console.log( "You pressed CTRL + Del" ); } 
like image 74
Sampson Avatar answered Oct 01 '22 20:10

Sampson


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         }       }     }) 
like image 44
Vaxo Basilidze Avatar answered Oct 01 '22 18:10

Vaxo Basilidze