10/05/2012

Capturing Shift+Enter Combination in Javascript

First we have to decide which 'first' key is pressed in a variable. For that reason we will create a 'flag' variable and that variable will change its status if the first key is pressed down and reset again if it is released.
Second part is easy, now we will get the 'second' key by checking the first's flag to distinguish between one key press and a combination press. A sample code is below:


var shiftKeyPressed = false;

document.onkeydown=function(e){
    
    if(e.keyCode == 16) shiftKeyPressed = true;
    
    if(e.keyCode == 13 && shiftKeyPressed == true) { // 13 for ENTER
        // code for SHIFT+ENTER
        return false; // cancel propagation
    }
}

document.onkeyup=function(e){
    if(e.keyCode == 16) // 16 for SHIFT
        shiftKeyPressed =false;
}
You can do more combinations just changing the key codes up there.