Luca Laiton
Luca Laiton

Reputation: 139

Simulate Enter In JavaScript

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?

Upvotes: 13

Views: 36321

Answers (3)

Dmytro Zasiadko
Dmytro Zasiadko

Reputation: 131

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.

Upvotes: 2

mliakos
mliakos

Reputation: 383

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
});

Upvotes: 16

Lewis
Lewis

Reputation: 14866

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);
 }

Upvotes: 2

Related Questions