Trigger a keypress/keydown/keyup event in JS/jQuery

In this article, we are going to discuss 2 methods of logging key-presses in web technologies using vanilla JavaScript as well as Jquery. We will also discuss the events related to key-presses in JavaScript. Firstly we have to create a structure so let’s make an HTML and CSS layout first.

HTML and CSS layout: In the given layout, when an input is made in the field, the keyCode value will be logged in the box.
The events related to keypresses are as follows :

  • keydown: This event is triggered when a key is pressed down.
  • keypress: This event is triggered when a key is pressed. This event fails to recognise keys such as tab, shift, ctrl, backspace etc.
  • keyup: This event is triggered when a key is released.
filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" 
              content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
  
        <style>
        h1 {
            color: green;
        }
        .display {
            border: 2px solid black;
            height: 100px;
            width: 400px;
            text-align: center;
        }
  
        .input {
            display: flex;
            flex-direction: column;
            font-size: 0px;
        }
        button {
            border: none;
            margin: 2px;
            width: 80px;
            height: 3vw;
            float: right;
            background-color: green;
            color: white;
        }
        button:hover {
            background-color: rgb(5, 94, 12);
        }
    </style>
    </head>
    <body>
        <h1>GeeksforGeeks</h1>
        <div class="display"><h3></h3></div>
        <div class="input">
            <button>emit event</button>
        </div>
    </body>
</html>

chevron_right


Output:

We shall achieve to trigger a keypress/keydown/keyup event in JS/jQuery using 2 methods:

  • Using Vanilla JavaScript: We will use the native dispatchEvent in order to create keyboard events as follows.

    We add an event listener to the button to trigger a series of events that will show ‘Hey Geek’ in the display division that we created. for this we have used dispatchEvent(new KeyboardEvent(…)). The KeyboardEvent is a constructor that takes an event and an object of event properties as parameters.



    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    window.addEventListener('load', ()=>{
        document.querySelector('button').addEventListener('click', ()=>{
            document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'H'}));
            document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'e'}));
            document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'y'}));
            document.dispatchEvent(new KeyboardEvent('keypress', {'key': ' '}));
            document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'G'}));
            document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'e'}));
            document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'e'}));
            document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'k'}));
        });
    });
    document.addEventListener('keypress', (event)=>{
        document.querySelector('h1').innerHTML += event.key;
    });

    chevron_right

    
    

  • Using jQuery: We first create an event e and assign the key property to it as shown in the above code. Using Jquery.trigger(e) we emit the event and handle it the same way we did in approach 1. However, instead of using innerHTML we use Jquery’s .append() method.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    $(document).ready(()=>{
           $('button').on('click', ()=>{
               let e = $.Event('keypress');
               e.key = 'H';
               $(document).trigger(e);
               e.key = 'e';
               $(document).trigger(e);
               e.key = 'y';
               $(document).trigger(e);
               e.key = ' ';
               $(document).trigger(e);
               e.key = 'G';
               $(document).trigger(e);
               e.key = 'e';
               $(document).trigger(e);
               e.key = 'e';
               $(document).trigger(e);
               e.key = 'k';
               $(document).trigger(e);
                 
           })
       });
       $(document).on('keypress', (event)=>{
             
           $('h1').append(event.key);
       })

    chevron_right

    
    

Final solution: We will simply use the approach 1 in this code, you can use any of them is as follows:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" 
              content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <script src="https://code.jquery.com/jquery-3.5.0.slim.js" 
                integrity="sha256-sCexhaKpAfuqulKjtSY7V9H7QT0TCN90H+Y5NlmqOUE="
                crossorigin="anonymous">
        </script>
            <style>
        h1 {
            color: green;
        }
        .display {
            border: 2px solid black;
            height: 100px;
            width: 400px;
            text-align: center;
        }
  
        .input {
            display: flex;
            flex-direction: column;
            font-size: 0px;
        }
        button {
            border: none;
            margin: 2px;
            width: 80px;
            height: 3vw;
            float: right;
            background-color: green;
            color: white;
        }
        button:hover {
            background-color: rgb(5, 94, 12);
        }
    </style>
    </head>
    <body>
        <h1>GeeksforGeeks</h1>
        <div class="display"><h3></h3></div>
        <div class="input">
            <button>emit event</button>
        </div>
        <script type="text/javascript">
            window.addEventListener("load", () => {
                document.querySelector("button").addEventListener("click", () => {
                    document.dispatchEvent(new KeyboardEvent("keypress", { key: "H" }));
                    document.dispatchEvent(new KeyboardEvent("keypress", { key: "e" }));
                    document.dispatchEvent(new KeyboardEvent("keypress", { key: "y" }));
                    document.dispatchEvent(new KeyboardEvent("keypress", { key: " " }));
                    document.dispatchEvent(new KeyboardEvent("keypress", { key: "G" }));
                    document.dispatchEvent(new KeyboardEvent("keypress", { key: "e" }));
                    document.dispatchEvent(new KeyboardEvent("keypress", { key: "e" }));
                    document.dispatchEvent(new KeyboardEvent("keypress", { key: "k" }));
                });
            });
  
            document.addEventListener("keypress", (event) => {
                document.querySelector("h3").innerHTML += event.key;
            });
        </script>
    </body>
</html>

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.