Open In App

HTML DOM KeyboardEvent key Property

Last Updated : 13 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The keyboardEvent key property in HTML is used to return the value of the key pressed when a key event occurs. It returns a single-character or multi-character string depending on which key is pressed. It is a read-only property. 

Syntax:

event.key

Return Value: It returns a string that represents the key pressed.

  • It can return single character strings like “a”, “5”, “+”, etc.
  • It can return a multi-character string like “F5”, “Enter”, “HOME”, etc.

Example: In this example, we will see the use of keyboardEvent key property

HTML




<html>
<head>
    <title>DOM keyboardEvent key Property</title>
</head>
<body style="text-align: center;">
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
    <h2>
        DOM keyboardEvent key Property
    </h2> Input:
    <input type="text" placeholder="Press any key..">
    <p id="p"></p>
    <script>
        // Adding a event listener function
        window.addEventListener("keydown", function (event) {
            let key = "key = '" +
                event.key + "'";
            // Creating a span element
            let element = document.createElement("span");
            element.innerHTML = key + "<br/>";
            // Appending the created element to paragraph
            document.getElementById("p").appendChild(element);
        }, true);
    </script>
</body>
 
</html>


Output:

 

 Supported Browsers: The browser supported by keyboardEvent key property are listed below:

  • Apple Safari 10.1
  • Google Chrome 51.0
  • Edge 12.0
  • Firefox 23.0
  • Opera 38.0
  • Internet Explorer 9.0


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads