Site icon port135.com

How to simulate keyboard key press in JavaScript using jQuery?

You may need your user to press a certain key as part of your application flow. Use the line below if you want to automatize this action. In this example, “77” is the character code for the letter “m”. Change it to the key you want to simulate pressing (JavaScript Key Codes).

jQuery.event.trigger({ type: 'keydown', which: 77 });

If you want to simulate the situation where user presses 2 keys at the same time in an input field, use the code block below. It assumes that user presses Alt + M

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

Note: Depending on the browser, you may need to use “keypress” event instead of “keydown” event.

References:

Exit mobile version