How to simulate a keypress event in JavaScript?

JavascriptWeb DevelopmentFront End Technology

To simulate a key press event, use event handlers. You can try to run the following code to simulate a key press event

Example

Live Demo

<html>
   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
      </script>
      <script>
         jQuery(document).ready(function($) {
            $('body').keypress(function(e) {
               alert(String.fromCharCode(e.which));
            });
         });
         jQuery.fn.simulateKeyPress = function(character) {
            jQuery(this).trigger({
               type: 'keypress',
               which: character.charCodeAt(0)
            });
         };
         setTimeout(function() {
            $('body').simulateKeyPress('z');
         }, 2000);
      </script>
   </head>
   <body>
      <p>press any key</p>
   </body>
</html>
raja
Published on 31-Jan-2018 14:20:31
Advertisements