Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
HTML DOM KeyboardEvent key Property
The KeyboardEvent key property returns the identifier of the key that was pressed during a keyboard event. This property provides the actual value of the key, making it useful for detecting specific characters, special keys, and modifiers in web applications.
Syntax
Following is the syntax for accessing the key property −
event.key
Where event is the KeyboardEvent object passed to the event handler function.
Return Value
The key property returns a string representing the key that was pressed. The returned values include −
Printable characters − Letters, numbers, symbols (e.g., "a", "A", "1", "@")
Special keys − Named keys like "Enter", "Escape", "Tab", "Backspace"
Modifier keys − "Shift", "Control", "Alt", "Meta"
Function keys − "F1", "F2", "F3", etc.
Arrow keys − "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"
Basic Example
Following example demonstrates the basic usage of the KeyboardEvent key property −
<!DOCTYPE html>
<html>
<head>
<title>KeyboardEvent key Property</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Key Detection Demo</h2>
<input type="text" id="keyInput" placeholder="Press any key..." style="padding: 10px; width: 300px;">
<p>Key pressed: <span id="keyDisplay" style="font-weight: bold; color: blue;">None</span></p>
<p>Key code: <span id="codeDisplay" style="font-weight: bold; color: green;">None</span></p>
<script>
document.getElementById('keyInput').addEventListener('keydown', function(event) {
document.getElementById('keyDisplay').textContent = event.key;
document.getElementById('codeDisplay').textContent = event.code;
});
</script>
</body>
</html>
When you type in the input field, the display shows both the key value and key code. Try pressing letters, numbers, and special keys like Enter or Escape.
Interactive Quiz Example
Following example shows a practical application using the key property for an interactive quiz −
<!DOCTYPE html>
<html>
<head>
<title>KeyboardEvent Quiz</title>
<style>
form {
width: 70%;
margin: 0 auto;
text-align: center;
font-family: Arial, sans-serif;
}
fieldset {
padding: 20px;
border-radius: 10px;
}
input[type="text"] {
padding: 10px;
font-size: 16px;
border-radius: 5px;
border: 2px solid #ccc;
}
#divDisplay {
margin-top: 15px;
font-weight: bold;
font-size: 18px;
}
.correct { color: green; }
.close { color: orange; }
.wrong { color: red; }
</style>
</head>
<body>
<form>
<fieldset>
<legend>KeyboardEvent Key Quiz</legend>
<label>Fill in the blank: __ for Ball
<input type="text" id="textSelect" placeholder="Press a key" onkeypress="getEventData(event)" autocomplete="off">
</label>
<div id="divDisplay">Type the first letter of "Ball"</div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var textSelect = document.getElementById("textSelect");
function getEventData(inputEvent) {
if(inputEvent.key === 'B') {
divDisplay.textContent = 'Correct Answer! Well done.';
divDisplay.className = 'correct';
}
else if(inputEvent.key === 'b') {
divDisplay.textContent = 'Close! Try using capital B.';
divDisplay.className = 'close';
}
else {
divDisplay.textContent = 'Try again. Think: B for Ball';
divDisplay.className = 'wrong';
}
// Clear input after each attempt
setTimeout(function() {
textSelect.value = '';
}, 100);
}
</script>
</body>
</html>
This quiz checks if the user presses the correct key ('B') and provides different feedback based on the input. The styling changes color based on the answer correctness.
Special Keys Detection
The key property is particularly useful for detecting special keys like function keys, arrows, and modifiers −
<!DOCTYPE html>
<html>
<head>
<title>Special Keys Detection</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Special Keys Demo</h2>
<p>Click in the text area and try pressing special keys like Enter, Escape, Arrow keys, F1-F12, etc.</p>
<textarea id="specialInput" style="width: 100%; height: 100px; padding: 10px;" placeholder="Press special keys here..."></textarea>
<div id="specialDisplay" style="margin-top: 10px; padding: 10px; background: #f0f0f0; border-radius: 5px;">
Press a special key to see its identifier
</div>
<script>
document.getElementById('specialInput').addEventListener('keydown', function(event) {
var display = document.getElementById('specialDisplay');
var keyName = event.key;
if(keyName.startsWith('Arrow')) {
display.innerHTML = '<strong>Arrow Key:</strong> ' + keyName + ' pressed';
}
else if(keyName.startsWith('F') && keyName.length <= 3) {
display.innerHTML = '<strong>Function Key:</strong> ' + keyName + ' pressed';
}
else if(['Enter', 'Escape', 'Tab', 'Backspace', 'Delete'].includes(keyName)) {
display.innerHTML = '<strong>Special Key:</strong> ' + keyName + ' pressed';
}
else if(['Shift', 'Control', 'Alt', 'Meta'].includes(keyName)) {
display.innerHTML = '<strong>Modifier Key:</strong> ' + keyName + ' pressed';
}
else {
display.innerHTML = '<strong>Key:</strong> "' + keyName + '" pressed';
}
});
</script>
</body>
</html>
This example categorizes different types of keys and displays appropriate messages for each category.
Key vs KeyCode vs Code
It's important to understand the difference between the various keyboard event properties −
| Property | Description | Example |
|---|---|---|
key |
The actual key value, affected by modifiers and layout | "a", "A", "Enter", "ArrowUp" |
code |
Physical key identifier, independent of layout | "KeyA", "Enter", "ArrowUp" |
keyCode (deprecated) |
Numeric code for the key, inconsistent across browsers | 65 for 'A', 13 for Enter |
Browser Compatibility
The key property is supported in all modern browsers −
Chrome − Version 51+
Firefox − Version 23+
Safari − Version 10.1+
Edge − Version 12+
Internet Explorer − Version 9+ (partial support)
For older browser compatibility, you may need to use keyCode as a fallback, though it's now deprecated.
Conclusion
The KeyboardEvent key property provides a reliable way to detect which key was pressed, returning human-readable string values for both printable characters and special keys. It's the modern standard for keyboard event handling and should be used instead of the deprecated keyCode property for new web applications.
