Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Emulate a space bar keypress

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?

like image 455
Oliver Avatar asked Dec 01 '15 10:12

Oliver


2 Answers

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

like image 138
R Lam Avatar answered Nov 03 '22 13:11

R Lam


Create your event variable like that :

var e = new Event('keydown');

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

like image 27
J. Gobet Avatar answered Nov 03 '22 14:11

J. Gobet