kathy
kathy

Reputation: 339

javascript how to detect keyboard input

when focusing on a certain input, user press kind of combination key such as "ctrl+e", I would like to show "ctrl+e" in the input.

next time user press another combination key, it will clean input and show the new one.

how can I make this? I look for some javascript plugins, but they are most for detecting certain input.

like this: https://github.com/OscarGodson/jKey

$("input").jkey("i",function(){
    jkey.log("You pressed the i key inside of an input.");
});

thanks a lot.

Upvotes: 1

Views: 2816

Answers (2)

Shakti
Shakti

Reputation: 161

Not all browsers allow the catching of cntrl keypress. This would work for the rest

$( document ).keypress(function(e) {
    var ch = String.fromCharCode(e.charCode);
    if(e.ctrlKey){
      console.log('cntrl+'+ch+' was pressed');
    }else{
      console.log(ch+' was pressed');
    }
});

Upvotes: 0

Mangesh Parte
Mangesh Parte

Reputation: 2177

Another approach (no plugin needed) it to just use .ctrlKey property of the event object that gets passed in. It indicates if Ctrl was pressed at the time of the event, like this:

$(document).keypress("c",function(e) {
  if(e.ctrlKey)
    alert("Ctrl+C was pressed!!");
});

Update

$(document).on('keypress','input',function(e){
    if ( e.ctrlKey && ( String.fromCharCode(e.which) === 'c' || String.fromCharCode(e.which) === 'C' ) ) {
        console.log( "You pressed CTRL + C" );
    }
});

Upvotes: 2

Related Questions