Home » Development » How to simulate keyboard key press in JavaScript using jQuery?

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:

Ned Sahin

Blogger for 20 years. Former Microsoft Engineer. Author of six books. I love creating helpful content and sharing with the world. Reach me out for any questions or feedback.

1 thought on “How to simulate keyboard key press in JavaScript using jQuery?”

  1. I found this script that works in TamperMonkey – https://stackoverflow.com/questions/65331341/greasemonkey-get-google-search-autocomplete-results/65331888#comment122035292_65331888

    I have severe carpal tunnel and want to minimize some of the keystrokes I have to perform often. Instead of the random keys this person uses for autocomplete, I just want to paste what is currently in the clipboard, submit it to Google search box and perform the search.

    I tried modifying the script with the following (as I understand these are the commands for ^V and Enter.

    Not sure if paste is recognized as a key command but I get no results from the clipboard to the search box.

    $(this).trigger($.Event(“keypress”, {keyCode: 86, ctrlKey: true}));
    $(this).trigger($.Event(“keypress”, {keyCode: 13}));

    Reply

Leave a Comment