Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to simulate key press events programmatically?

Is it possible to simulate key press events programmatically in JavaScript?

like image 212
tan Avatar asked Feb 27 '09 20:02

tan


People also ask

Are keypress events deprecated?

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.

How do I trigger an event on my keyboard?

keydown: This event is triggered when a key is pressed down. keypress: This event is triggered when a key is pressed. This event fails to recognise keys such as tab, shift, ctrl, backspace etc. keyup: This event is triggered when a key is released.

How do you trigger keypress event in react JS?

If you're trying to create a keyboard event, you can make use of KeyboradEvent constructor. An enter key event can be dispatched like: const event = new KeyboardEvent('keypress', { key: 'enter', }); console. log(event) // KeyboardEvent {isTrusted: false, key: "enter", code: "", location: 0, ctrlKey: false, …}


1 Answers

A non-jquery version that works in both webkit and gecko:

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, // view: should be window   false, // ctrlKey   false, // altKey   false, // shiftKey   false, // metaKey   40, // keyCode: unsigned long - the virtual key code, else 0   0, // charCode: unsigned long - the Unicode character associated with the depressed key, else 0 ); document.dispatchEvent(keyboardEvent);
like image 62
Philip Nuzhnyy Avatar answered Sep 21 '22 19:09

Philip Nuzhnyy