Simulate pressing a key in Javascript

By xngo on February 20, 2019

Requirement

  • Download jquery.sendkeys.js and bililiteRange.js and add them in your HTML file.
  • More information can be found at http://bililite.com/blog/2011/01/23/improved-sendkeys/.

The code

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript" src="jquery.sendkeys.js"></script>
        <script type="text/javascript" src="bililiteRange.js"></script>
 
        <script type="text/javascript">
        /*************************************************
        * Example showing how to simulate pressing a key.
        *************************************************/
 
        function pressChar(char)
        {
            $('#input_field').trigger({type: 'keydown', key: char});
 
            // or
            //$('#input_field').sendkeys(char);
 
        }
        </script>
 
 
        <title>Simulate pressing a key</title>
    </head>
 
    <body>
        <button onclick="pressChar('s')">Click on this button to simulate 
                                        the 's' key is being pressed.</button>
        <input type="text" id="input_field" />
    </body>
 
</html>

The output

Simulate key press screenshot

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.