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 onkeydown Event Attribute
The HTML onkeydown event attribute is triggered when a user presses a key on the keyboard. This event fires at the moment a key is pressed down, before the key is released. It is commonly used for capturing keyboard input, creating keyboard shortcuts, and implementing real-time text processing.
The onkeydown event occurs in the following sequence: onkeydown ? onkeypress ? onkeyup. The onkeydown event fires for all keys including function keys, arrow keys, and special keys like Escape or Tab.
Syntax
Following is the syntax for the onkeydown event attribute −
<tagname onkeydown="script">Content</tagname>
Where script is the JavaScript code to execute when the key is pressed down.
Parameters
The onkeydown event handler receives an event object that contains information about the key press −
event.key − Returns the actual key that was pressed (e.g., "a", "Enter", "Escape")
event.keyCode − Returns the numeric key code (deprecated but still widely supported)
event.which − Similar to keyCode (deprecated)
event.code − Returns the physical key on the keyboard (e.g., "KeyA", "Enter")
Basic Text Input Example
Following example demonstrates the onkeydown event with a text input field −
<!DOCTYPE html>
<html>
<head>
<title>onkeydown Event Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>HTML onkeydown Event Demo</h2>
<input type="text" placeholder="Type something..." onkeydown="showKey(event)" style="padding: 8px; font-size: 16px;">
<p id="output">Press any key in the input field...</p>
<script>
function showKey(event) {
document.getElementById("output").innerHTML =
"Key pressed: " + event.key + " (Key code: " + event.keyCode + ")";
}
</script>
</body>
</html>
The output shows the key information whenever a key is pressed in the input field −
Key pressed: a (Key code: 65) Key pressed: Enter (Key code: 13) Key pressed: Backspace (Key code: 8)
Textarea with Character Count
Following example shows how to use onkeydown to create a real-time character counter −
<!DOCTYPE html>
<html>
<head>
<title>Character Counter Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Character Counter with onkeydown</h2>
<textarea rows="4" cols="50" placeholder="Type your message here..."
onkeydown="updateCounter()"
style="padding: 8px; font-size: 14px;"></textarea>
<p>Characters typed: <span id="counter">0</span></p>
<script>
function updateCounter() {
setTimeout(function() {
var text = document.querySelector("textarea").value;
document.getElementById("counter").textContent = text.length;
}, 10);
}
</script>
</body>
</html>
The character count updates in real-time as the user types. The setTimeout is used because onkeydown fires before the character is added to the textarea.
Characters typed: 25 (Updates as user types in the textarea)
Preventing Default Behavior
The onkeydown event can prevent certain keys from functioning by using event.preventDefault(). Following example blocks numeric input −
<!DOCTYPE html>
<html>
<head>
<title>Block Numbers Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Text-Only Input Field</h2>
<input type="text" placeholder="Letters only..."
onkeydown="blockNumbers(event)"
style="padding: 8px; font-size: 16px;">
<p>Try typing numbers - they will be blocked!</p>
<p id="message"></p>
<script>
function blockNumbers(event) {
// Block number keys (0-9)
if (event.keyCode >= 48 && event.keyCode <= 57) {
event.preventDefault();
document.getElementById("message").innerHTML =
"<span style='color: red;'>Numbers are not allowed!</span>";
setTimeout(function() {
document.getElementById("message").innerHTML = "";
}, 2000);
}
}
</script>
</body>
</html>
When a user tries to type numbers, the input is blocked and an error message appears temporarily.
Keyboard Shortcuts Example
Following example demonstrates how to create keyboard shortcuts using onkeydown −
<!DOCTYPE html>
<html>
<head>
<title>Keyboard Shortcuts</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;" onkeydown="handleShortcuts(event)">
<h2>Keyboard Shortcuts Demo</h2>
<p>Try these shortcuts:</p>
<ul>
<li>Ctrl + S = Save message</li>
<li>Ctrl + R = Reset</li>
<li>Escape = Clear message</li>
</ul>
<div id="status" style="padding: 10px; background: #f0f0f0; margin-top: 10px;">
Press a shortcut key...
</div>
<script>
function handleShortcuts(event) {
var status = document.getElementById("status");
if (event.ctrlKey && event.key === 's') {
event.preventDefault(); // Prevent browser save dialog
status.innerHTML = "<span style='color: green;'>? Document saved!</span>";
} else if (event.ctrlKey && event.key === 'r') {
event.preventDefault(); // Prevent browser refresh
status.innerHTML = "<span style='color: orange;'>? Reset complete!</span>";
} else if (event.key === 'Escape') {
status.innerHTML = "Press a shortcut key...";
}
}
</script>
</body>
</html>
The shortcuts work anywhere on the page and provide visual feedback when activated.
? Document saved! (when Ctrl+S is pressed) ? Reset complete! (when Ctrl+R is pressed) Press a shortcut key... (when Escape is pressed)
Common Use Cases
The onkeydown event is commonly used for −
Form validation − Restricting input types (numbers-only, letters-only)
Keyboard shortcuts − Implementing application hotkeys
Real-time processing − Character counting, search suggestions
Game controls − Capturing arrow keys for movement
Navigation − Custom tab handling or enter key submissions
Comparison with Other Keyboard Events
| Event | When Triggered | Repeats on Hold | Best Use Case |
|---|---|---|---|
| onkeydown | Key is pressed down | Yes | Keyboard shortcuts, input validation |
| onkeypress | Character key produces output | Yes | Character input (deprecated) |
| onkeyup | Key is released | No | Final processing after input |
Conclusion
The HTML onkeydown event attribute is essential for capturing keyboard interactions in web applications. It fires when any key is pressed down and can be used for input validation, keyboard shortcuts, and real-time text processing. Unlike onkeypress, onkeydown works with all keys including function keys and arrow keys, making it the preferred choice for comprehensive keyboard handling.
