Invoking KeyPress Event Without Actually Pressing Key

10,587

Solution 1

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

Solution 2

If you're using jquery:

var e = jQuery.Event("keydown");
e.which = 50; //key code
$("#some_element").trigger(e);
Share:
10,587
skos
Author by

skos

Updated on June 15, 2022

Comments

  • skos
    skos about 2 years

    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.