Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking KeyPress Event Without Actually Pressing Key

Just wondering. Is it possible to invoke a key press event in JavaScript without ACTUALLY pressing the key ? For example lets say, I have a button on my webpage and when that button is clicked I want to invoke a event as if a particular key has been pressed. I know it weird but can this be done in JavaScript.

like image 453
skos Avatar asked May 09 '12 10:05

skos


People also ask

What can I use instead of a keypress event?

When in editing contexts, authors can subscribe to the beforeinput event instead. You can also use the keydown and/or keyup events.

How do you trigger a keypress event?

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift , Esc , and delete trigger keydown events but not keypress events.

Can Javascript simulate key presses?

If you need keyup events too, it is also possible to simulate keyup events by changing "keydown" to "keyup" in the code snippet. This also sends the event to the entire webpage, hence the document . If you want only a specific element to receive the event, you can substitute document for the desired element.

What is the difference between keypress () and Keydown ()?

keydown – fires when any key is pressed down, fires first, and always before the browser processes the key (e.g. inserting text, moving focus, etc). keypress – fires when a key that produces a character value is pressed down, fires after keydown , and before the browser processes the key.


1 Answers

Yes, this can be done using initKeyEvent. It's a little verbose to use, though. If that bothers you, use jQuery, as shown in @WojtekT's answer.

Otherwise, in vanilla javascript, this 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 );
like image 118
Florian Margaine Avatar answered Sep 22 '22 18:09

Florian Margaine