Javascript – js – simulate key press without specifying an element

javascriptkeykeyboardsimulatetesting

i would like to simulate a key press in js. preferably without specifying any element.

the way i would like to do it is to use .focus() on an input and then simulate a key press like the character "a".

just the same thing that would happen if i would press the key myself.

searching through the internet i found no solution. it might have something to do with the combination of the simulated event and an input field. sometimes i can catch the events, but there is no input present in the input field.

thank you very much in advance for any help.

EDIT 1:
this should not be considered a dublicate of: Is it possible to simulate key press events programmatically?

because this does not solve my problem. i have already tried it.

EDIT 2:
please do not downvote this question just because you do not know how to answer it.

Best Answer

If you have or can include jQuery, here's the easy way

With jQuery

jQuery.event.trigger({ type: 'keydown', which: 78 }); // press n key

To simulate the keypress event within an input field, use like this

var e = jQuery.Event("keydown");
e.which = 78; // n code value
e.altKey = true; // Alt key pressed
$("#inputBox").trigger(e);

Without jQuery

var kbEvent= document.createEvent("KeyboardEvent");
var initMethod = typeof kbEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";

kbEvent[initMethod](
                   "keydown", // event type : keydown, keyup, keypress
                    true, // bubbles
                    true, // cancelable
                    window, // viewArg: should be window
                    false, // ctrlKeyArg
                    false, // altKeyArg
                    false, // shiftKeyArg
                    false, // metaKeyArg
                    78, // keyCodeArg : unsigned long the virtual key code , else 0
                    0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
document.dispatchEvent(kbEvent);

The above code infact will not modify the input value for you, it will only simulate keystrokes

See this post for more info How to simulate typing in input field using jQuery?

What you need is : fn.sendKeys