1

The following jQuery-less code works:

var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";

keyboardEvent[initMethod](
               "keydown", // event type : keydown, keyup, keypress
                true, // bubbles
                true, // cancelable
                window, // viewArg: should be window
                false, // ctrlKeyArg
                false, // altKeyArg
                false, // shiftKeyArg
                false, // metaKeyArg
                17, // keyCodeArg : unsigned long the virtual key code, else 0
                0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
element.dispatchEvent(keyboardEvent);

... and should work in many browsers, opposed to this simpler solution:
jQuery keydown trigger not working

I tried to find a way to let jQuery do the same, but unfortunately, the following code does not work:

var evt = $.Event('keydown');
evt.which = 17;
evt.keyCode = 17; // Ctrl
$(element).trigger(evt);


Here's the full GreaseMonkey script if you want to test your solutions:
http://userscripts.org/scripts/review/486617

Community
  • 1
  • 1
CodeManX
  • 11,159
  • 5
  • 49
  • 70
  • http://jsfiddle.net/YzjgR/ – adeneo May 04 '14 at 20:02
  • It works in your example, but not in my script (see link in question). It looks as if jQuery creates a different event or doesn't dispatch it the same way as the native JavaScript code does. I'm using Firefox 28.0 on Windows 7. – CodeManX May 04 '14 at 20:10
  • And did you use it like in the fiddle, without the `$.Event` call. `keydown` is a native event, you don't create a new event to trigger a native event that already exists – adeneo May 04 '14 at 20:24
  • Exactly like in your fiddle, but nothing. I need to create a native event of type 'keydown', there is no other keyevent. I need to fake some key event when my injected button is clicked, to get the Markdown live preview updated. – CodeManX May 04 '14 at 20:54
  • Then I have no idea, just stick with the native code I suppose ? – adeneo May 04 '14 at 21:00

0 Answers0