I'm trying to simulate a keyboard event in Safari using JavaScript.
I have tried this:
var event = document.createEvent("KeyboardEvent");
event.initKeyboardEvent("keypress", true, true, null, false, false, false, false, 115, 0);
...and also this:
var event = document.createEvent("UIEvents");
event.initUIEvent("keypress", true, true, window, 1);
event.keyCode = 115;
After trying both approaches, however, I have the same problem: after the code has been executed, the keyCode
/which
properties of the event object are set to 0
, not 115
.
Does anyone know how to reliably create and dispatch a keyboard event in Safari? (I'd prefer to achieve it in plain JavaScript if possible.)
This is due to a bug in Webkit.
You can work around the Webkit bug using
createEvent('Event')
rather thancreateEvent('KeyboardEvent')
, and then assigning thekeyCode
property. See this answer and this example.I am working on DOM Keyboard Event Level 3 polyfill . In latest browsers or with this polyfill you can do something like this:
UPDATE:
Now my polyfill supports legacy properties "keyCode", "charCode" and "which"
Examples here
Additionally here is cross-browser initKeyboardEvent separately from my polyfill: (gist)
Polyfill demo
Did you dispatch the event correctly?
If you use jQuery, you could do:
The Mozilla Developer Network provides the following explanation:
event = document.createEvent("KeyboardEvent")
using:
yourElement.dispatchEvent(event)
I don't see the last one in your code, maybe that's what you're missing. I hope this works in IE as well...
I am not very good with this but
KeyboardEvent
=> see KeyboardEvent is initialized withinitKeyEvent
.Here is an example for emitting event on
<input type="text" />
element