KeyPress event call without pressing a key

Just wondering. Is it possible to trigger a key pressing event in JavaScript without clicking the ACTIVE button? For example, let's say I have a button on my web page, and when this button is pressed, I want to trigger an event as if a specific key had been pressed. I know this is weird, but it can be done in JavaScript.

+4
source share
2 answers

Yes, this can be done using initKeyEvent . However, this is a little useful. If this bothers you, use jQuery as shown in @WojtekT .

Otherwise, in vanilla javascript, here is how it works:

// Create the event var evt = document.createEvent( 'KeyboardEvent' ); // Init the options evt.initKeyEvent( "keypress", // the kind of event true, // boolean "can it bubble?" true, // boolean "can it be cancelled?" null, // specifies the view context (usually window or null) false, // boolean "Ctrl key?" false, // boolean "Alt key?" false, // Boolean "Shift key?" false, // Boolean "Meta key?" 9, // the keyCode 0); // the charCode // Dispatch the event on the element el.dispatchEvent( evt ); 
+4
source

If you are using jquery:

 var e = jQuery.Event("keydown"); e.which = 50; //key code $("#some_element").trigger(e); 
+3
source

Source: https://habr.com/ru/post/1411491/


All Articles