Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hold a keypress (Shift Key) in Javascript/Jquery

Here we are not checking that the shiftkey is pressed or not. What i need is to press shiftkey on a function call

We have code where a key can be pressed on element keypress.

e = jQuery.Event("keypress");
e.which = 13 //choose the one you want
   $("#test").keypress(function(){
    alert('keypress triggered');
}).trigger(e);

My requirement is Shift Key should be kept pressed on my function and released on another function called.

function called(){
   .. code ..
   // need shift key pressed
}

function called_another_func(){
   .. code ..
   // need shift key released
}
like image 356
Anupam Bhatt Avatar asked Nov 07 '22 02:11

Anupam Bhatt


1 Answers

Continuous Shift key press can be triggered programmatically by below code (16 is shift key keycode):

$("selector").keydown(function(event){
    if(event.which === 16){
        //any code you want to execute before key press
        e=$.Event('keydown')
        e.which=16
        $("selector").trigger(e)
    }
});

However this may hang the application because of recursive event calls and throw an error in console. To prevent this you will have to do something like this:

$("selector").keydown(function(event){
    if(event.which === 16){
        if("flag to check if you need to continue shift key press"){
            //any code (or function call) you want to execute before key press and 
            //toggle the variable to break out of this recursive event trigger 
            e=$.Event('keydown')
            e.which=16
            $("selector").trigger(e)
        }
    }
});
$("selector").keyup(function(event){
    if(event.which === 16){
            //call your function
        }
    });
});
like image 168
binf Avatar answered Nov 14 '22 23:11

binf