13

I try to simulate Enter in JavaScript in a specific TextArea. This is my code:

 function enter1() {
       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
            13, // keyCodeArg : unsigned long the virtual key code, else 0
            13 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
       );
       document.getElementById('text').dispatchEvent(keyboardEvent);
 }

TextArea:

<textarea id="text"> </textarea>

When I call enter1(), it doesn't do anything in the TextArea. Why is this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Luca Laiton
  • 139
  • 1
  • 1
  • 4
  • [here](http://stackoverflow.com/questions/961532/firing-a-keyboard-event-in-javascript), [here](http://stackoverflow.com/questions/10455626/keydown-simulation-in-chrome-fires-normally-but-not-the-correct-key) – alessandrio May 02 '15 at 15:17
  • @avrilalejandro thanks avril alejandro for support, but every function failed with "enter". I don't understand. – Luca Laiton May 02 '15 at 16:58
  • OP will probably never come back, but for future readers that come here with the same question, you are facing an XY problem. **No you do not want to fire an Enter event**. What you want is to produce the same actions such an Event generally produce. Here it will be hard to know for sure what it was, but maybe they wanted to insert a new line? Then insert a new line. Maybe they had an event listener that would trigger a third action? Then just call that third action directly. – Kaiido Sep 22 '19 at 12:32

3 Answers3

15

For anyone that has a problem dispatching the event, try adding the key-value pair bubbles: true:

const keyboardEvent = new KeyboardEvent('keydown', {
    code: 'Enter',
    key: 'Enter',
    charCode: 13,
    keyCode: 13,
    view: window,
    bubbles: true
});
mliakos
  • 373
  • 2
  • 9
2

I think it's a browser bug since keyboardEvent.which is unwritable. In order to fix it, you have to delete keyboardEvent.which property before assigning the keycode.

 function enter1() {
   var keyboardEvent = document.createEvent('KeyboardEvent');
   delete keyboardEvent.which;
   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
     13, // keyCodeArg : unsigned long the virtual key code, else 0
     13 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
   );
   document.getElementById('text').dispatchEvent(keyboardEvent);
 }

An alternative solution is KeyboardEvent Constructor. Just be careful with the compatibility issue.

 function enter1() {
   var keyboardEvent = new KeyboardEvent('keydown');
   delete keyboardEvent.which;
   keyboardEvent.which = 13;
   document.getElementById('text').dispatchEvent(keyboardEvent);
 }
Lewis
  • 14,132
  • 12
  • 66
  • 87
  • i edited the code, but nothing changed. thanks for your answer. – Luca Laiton May 02 '15 at 15:41
  • @LucaLaiton You can try manually assigning `keyboardEvent.which = 13;` instead of passing keycode into `initMethod`. – Lewis May 02 '15 at 15:45
  • function premi_enter() { var keyboardEvent = document.createEvent('KeyboardEvent'); delete keyboardEvent.which; keyboardEvent.which = 13; document.getElementById('text').dispatchEvent(keyboardEvent); } – Luca Laiton May 02 '15 at 15:52
  • @LucaLaiton Yes. BTW, I've updated my answer with a more elegant solution. I thought you may be interested in it. – Lewis May 02 '15 at 15:54
  • thanks for support, but the last one function doesn't work for compatibility, maybe. I need only simulate the pressing of enter key, for me is very hard :) – Luca Laiton May 02 '15 at 17:02
  • I have the same problem and I still can't get that working – Reem Aug 10 '17 at 15:13
2

var textArea = document.getElementById('text');
function enter() {
    var keyboardEvent = new KeyboardEvent('keydown', {
        code: 'Enter',
        key: 'Enter',
        charCode: 13,
        keyCode: 13,
        view: window
    });

    textArea.dispatchEvent(keyboardEvent);
}

textArea.addEventListener('keydown', function (e) {
    console.log(e);
});
enter()
<!doctype html>
<html class="no-js" lang="">

<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>test</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>

<body>
    <textarea id="text"></textarea>
</body>

</html>

At this moment initKeyboardEvent method is marked as deprecated. It is recommended to instantiate KeyboardEvent directly and pass necessary data to constructor - link. See the browser compatibility section. At least it works in chrome and firefox.

Michael Johansen
  • 4,688
  • 5
  • 29
  • 47
  • This approach looks obsolete now. https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode – SFin Jul 30 '18 at 15:18
  • @SFin I removed the charKode and keyCode properties and this solution worked for me. – C.M. Jun 18 '20 at 18:32