Keyboard events allow you to capture every keystroke a user makes on their keyboard. This is essential for creating live-search features, performing real-time form validation, or building custom keyboard shortcuts for your web application.
There are three main events triggered during the process of pressing a key. They always happen in a specific order:
Occurs at the exact moment a key is **pressed down**. It fires immediately and will repeat if the key is held down.
Occurs when a **character** is being inserted. (Note: Many modern browsers are phasing this out in favor of keydown).
Occurs when the user **releases** the key. This is the best moment to check the final value of an input field.
To detect which specific key was pressed (like Enter, Escape, or an Arrow key), you use the **event** object that is passed into the handler function.
$("input").keydown(function(event) {
// Each key has a unique numeric code called "which"
console.log("Key code: " + event.which);
// You can also use "event.key" for the actual name
console.log("Key pressed: " + event.key);
});
A common requirement is to trigger an action when a user finishes typing and presses Enter (code 13).
$("#search").keyup(function(event) {
if (event.which == 13) {
alert("Searching for: " + $(this).val());
}
});
You can use keyup() to update a character count in real-time as a user types
into a text area.
<textarea id="message" maxlength="100"></textarea>
<p>Characters left: <span id="count">100</span></p>
<script>
$("#message").keyup(function() {
var length = $(this).val().length;
var left = 100 - length;
$("#count").text(left);
});
</script>
| Method | Best For... |
|---|---|
keydown() |
Keyboard shortcuts (e.g., Ctrl+S) or games where reaction speed matters. |
keyup() |
Validating input or updating UI after a change is finalized. |
keypress() |
Legacy support for detecting punctuation and letter cases (deprecated). |