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