0

I would like to fake an 'enter' keypress event in the browser, without the help of jQuery.

Here's what I tried :

var keyEvent = document.createEvent('KeyboardEvent');
keyEvent.initKeyboardEvent('keyup', true, false, null, 0, false, 0, false, 13, 0);
elem.dispatchEvent(keyEvent);

where elem is one particular element (found with document.querySelector())

However the Javascript console tells me initKeyboardEvent() is not a function.

Now, the documentation does say here that this function is deprecated, but doesn't redirect to the right way to do it nowadays, and I couldn't find any example of how to achieve this by myself either.

Any help on that one?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nicolas Marshall
  • 4,186
  • 9
  • 36
  • 54
  • @Juhana The post you're referring to has an answer using `initKeyEvent()` which is **also** deprecated (just like `initKeyboardEvent()`. MDN documentation says: "Do not use this method any more, use the KeyboardEvent() constructor instead." – marekful Sep 08 '15 at 10:22
  • @NicolasM The redirect you're looking for goes here: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent – marekful Sep 08 '15 at 10:25
  • The duplicate also has an answer using `KeyboardEvent`. – JJJ Sep 08 '15 at 10:29
  • It is a duplicate, indeed ! Sorry for not noticing ! The answer with `KeyboardEvent` is the one i used, it gets straight to the point. Thanks ! – Nicolas Marshall Sep 08 '15 at 12:10

0 Answers0