7

I've searched everywhere, read the docs on MDN, but I can't seem to solve this problem.

I want to emulate the client pressing the space bar using JavaScript.

I've tried:

var e = new KeyboardEvent('keydown');
e.which = e.keyCode = 32; // 32 is the keycode for the space bar
document.dispatchEvent(e);

However this hasn't worked for whatever reason; if the following event handler is put before the above code:

document.addEventListener('keydown', function(ev){
  console.log(ev.which);
});

0 is logged to the console.

For some reason, the event is triggered but the key is always 0

Can someone help me fix it?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Oliver
  • 1,576
  • 1
  • 17
  • 31
  • 1
    @Satpal The API used in the answer there is deprecated now. I have tried using the answer but it failed. – Oliver Dec 01 '15 at 10:14

2 Answers2

8

You may do on this way

var e = new KeyboardEvent('keydown',{'keyCode':32,'which':32});

Demo: https://jsfiddle.net/5se13tmg/

Reference: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent

R Lam
  • 393
  • 1
  • 13
  • Warning for others finding this: this is not IE compatible. There is more discussion on how to get around that here: https://stackoverflow.com/questions/26596123/internet-explorer-9-10-11-event-constructor-doesnt-work – Alexandra Oct 04 '18 at 20:53
5

Create your event variable like that :

var e = new Event('keydown');

Demo : https://jsfiddle.net/zw7d7d61/

J. Gobet
  • 179
  • 1
  • 5