How to useevent.key property in Javascript

  • Take the input from the input element and add an event listener to the input element using the .addEventListener() method on onkeydown event.
  • Use event.key inside the anonymous function called in the add event listener method to get the key pressed.
  • Check if the key pressed is Backspace or Delete.

Example 1: This example implements the above approach.

html




<!DOCTYPE HTML>
<html>
 
<head>
    <title>
        Capture the backspace and delete on the onkeydown event.
    </title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
    </script>
</head>
 
<body style="text-align:center;">
    <h1 style="color:green;">
        w3wiki
    </h1>
    <p id="GFG_UP">
    </p>
    Type Here:
    <input id="inp" />
    <br>
    <p id="GFG_DOWN" style="color: green;">
    </p>
    <script>
        let up = document.getElementById('GFG_UP');
        let down = document.getElementById('GFG_DOWN');
        let el = document.getElementById('inp');
        up.innerHTML =
              "Type in the input box to determine the pressed.";
        el.addEventListener('keydown', function (event) {
            const key = event.key;
            if (key === "Backspace" || key === "Delete") {
                $('#GFG_DOWN').html(key + ' is Pressed!');
            }
        });
    </script>
</body>
 
</html>


Output:

Output

Ways to capture the backspace and delete on the onkeydown event

Given the HTML document. The task is to detect when the backspace and delete keys are pressed on keydown events. Here 2 approaches are discussed, one uses event.key and another uses event.keyCode with the help of JavaScript.

These are the following methods:

Table of Content

  • Using event.key property
  • Using event.keyCode Property

Similar Reads

Approach 1: Using event.key property

Take the input from the input element and add an event listener to the input element using the .addEventListener() method on onkeydown event. Use event.key inside the anonymous function called in the add event listener method to get the key pressed. Check if the key pressed is Backspace or Delete....

Approach 2: Using event.keyCode Property

...

Contact Us