-1

How would I simulate the enter key being hit on a webpage by using KeyboardEvent(). All of the older questions I see use deprecated things according to https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent and they do not work in chrome. Using new KeyboardEvent works but it does not actually execute the event in the browser

McMatt
  • 129
  • 1
  • 14
  • 1
    [`dispatchEvent`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent) deprecated? Since when? – Teemu Feb 06 '17 at 17:50
  • 1
    Have you actually read the docs? https://www.w3.org/TR/uievents/ doesn't indicate any deprecation (unless you mean in Windows...) – Snowmonkey Feb 06 '17 at 17:51
  • @Teemu sorry meant to say that most the things used are deprecated and using dispatchEvent does not work in the latest chrome browser. – McMatt Feb 06 '17 at 18:02
  • What is the latest Chrome version? [Seems to work fine](https://jsfiddle.net/s8zx67my/) in version 56.0.2924.87. – Teemu Feb 06 '17 at 18:20

2 Answers2

2

A jQuery solution according to the jQuery - Event():

$('#targetElement').trigger(jQuery.Event('keydown', {which: $.ui.keyCode.ENTER }));
Mateusz Kleinert
  • 1,316
  • 11
  • 20
0

The key code for enter is 13 so here is the code.

<body onkeypress="runThis(event)">

 function runThis(e){
            if (e.keyCode == 13) {
                console.log("You clicked enter");
            }
        }

</body>

I hope this one solve your issue

skid
  • 958
  • 4
  • 13
  • 29
  • Your code doesn't trigger the event. It only checks if the user have pressed the enter key. – Mateusz Kleinert Feb 06 '17 at 17:59
  • This is not what I was looking for. I just want to trigger the event not handle it. – McMatt Feb 06 '17 at 18:00
  • 1
    http://stackoverflow.com/questions/596481/is-it-possible-to-simulate-key-press-events-programatically is this the one which your are looking for – skid Feb 06 '17 at 18:03