Simulate JavaScript key

-3

Good morning,

I have a game in JS that requires a keyboard. Two keys The change of the keys is quite compliant. I want to add a button that simulates the pressing of that key.

<button onclick="presskey('32')">A</button>


function pressKey(i)
  {var keyboardEvent = i;
   document.dispatchEvent(keyboardEvent);
      }

Something like that could be logic

    
asked by Angel Prieto 25.10.2017 в 17:31
source

1 answer

1

You have to create a new KeyboardEvent . Initialize it and give it the property of the key you want to simulate.

The documentation of KeyboardEvent has never been very clear to me. Some recommend using key and others using which . Now I did the test and the following example does not send the charcode 32, but it does simulate pressing Space.

var event = new KeyboardEvent("keydown", {which:32,  key:' ', code:'Space',keyCode:32, charCode:32});
document.dispatchEvent(event);

Apparently this is Chrome's own behavior because it works in Firefox. In Chrome I found the following (taken from an example in jsbin )

var eventObj = document.createEventObject ?
    document.createEventObject() : document.createEvent("Events");

if(eventObj.initEvent){
  eventObj.initEvent("keydown", true, true);
}

eventObj.keyCode = 32;
eventObj.which = 32;
eventObj.key=' ';
eventObj.code='Space';
document.dispatchEvent ? document.dispatchEvent(eventObj) : document.fireEvent("onkeydown", eventObj); 
    
answered by 25.10.2017 в 19:42