HTML | DOM KeyboardEvent key Property

The keyboardEvent key property in HTML is used to return the value of 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 which represents the key pressed.

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

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<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) {
            var key = "key = '" +
                event.key + "'";
  
            // Creating a span element
            var element = document.createElement("span");
            element.innerHTML = key + "<br/>";
  
            // Appending the created element to paragraph
            document.getElementById("p").appendChild(element);
        }, true);
    </script>
</body>
  
</html>

chevron_right


Output:

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

  • Apple Safari Not supported
  • Google Chrome 51.0
  • Firefox 23.0
  • Opera 38.0
  • Internet Explorer 9.0


My Personal Notes arrow_drop_up


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.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.