Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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.




<!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>


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.




    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;
    });

    
    

  • 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.




    $(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);
       })

    
    

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




<!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>


Output:

jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.
You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.



Last Updated : 03 Aug, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads