0

I need to simulate a key press. However I have just been able to find this:

var press = jQuery.Event("keypress");
press.ctrlKey = false;
press.which = 75;
$("whatever").trigger(press);

Where "whatever" is an input field or something. However I don't need to target any element. How can I simulate a key press (the 'k' key to be specific) without targeting any element?

Erazihel
  • 7,295
  • 6
  • 30
  • 53
123a
  • 21
  • 2
  • Possible duplicate of [How to trigger event in JavaScript?](https://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript) – Erazihel Jul 12 '17 at 12:08
  • Maybe this helps: https://stackoverflow.com/questions/596481/is-it-possible-to-simulate-key-press-events-programmatically – Kloker Jul 12 '17 at 12:09
  • Where is the key being pressed if not somewhere in the interface? – David Jul 12 '17 at 12:09
  • 1
    i guess your target element can be body, document or window (i would go for body, it is here i used to place the keypressed events) – Kaddath Jul 12 '17 at 12:13

3 Answers3

0

if you dont want to target any element, you will have to target the body directly, that way, any key should trigger what you want

$(document).ready(function(){
    $("body").keypress(function(){
        alert('hey');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Jonathan
  • 2,700
  • 4
  • 23
  • 41
0

Targeting the body will give you the sense of targeting nothing.

CharCode()

function showChar(e)
{
alert("Key Pressed: " + String.fromCharCode(e.charCode) + "\n"
      + "charCode: " + e.charCode);
}
<body onkeypress="showChar(event);">
dale landry
  • 7,831
  • 2
  • 16
  • 28
0

Do it like this:

$('body').keypress(function(e){
  if ( e.which == 75 ) { 
    alert('hey k was pressed');
  }
});

Have a look at this list of char codes

Evhz
  • 8,852
  • 9
  • 51
  • 69