14

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?

3
  • here, here Commented May 2, 2015 at 15:17
  • @avrilalejandro thanks avril alejandro for support, but every function failed with "enter". I don't understand. Commented May 2, 2015 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. Commented Sep 22, 2019 at 12:32

3 Answers 3

17

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
});
Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

@SFin I removed the charKode and keyCode properties and this solution worked for me.
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);
 }

6 Comments

i edited the code, but nothing changed. thanks for your answer.
@LucaLaiton You can try manually assigning keyboardEvent.which = 13; instead of passing keycode into initMethod.
<pre> <code> function premi_enter() { var keyboardEvent = document.createEvent('KeyboardEvent'); delete keyboardEvent.which; keyboardEvent.which = 13; document.getElementById('text').dispatchEvent(keyboardEvent); } </pre> </code>
@LucaLaiton Yes. BTW, I've updated my answer with a more elegant solution. I thought you may be interested in it.
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 :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.