Keyboard Events
In this page:
Keydown
The keydown event fires the instant a key is pressed down, before the character (if any) is registered. This makes it the right event to catch non-printing keys like arrow keys or Escape.
Example: Keydown
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="field">
<script>
$("#field").on("keydown", function(event) {
console.log("Key pressed down:", event.key);
});
</script>
</body>
</html>
Keyup
keyup fires once a pressed key is released, which makes it useful for reacting after a full keystroke has completed rather than while it's still being held. This is the natural event to use when you want to react to the final character typed, rather than every intermediate keystroke.
Example: Keyup
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="field">
<script>
$("#field").on("keyup", function(event) {
console.log("Key released:", event.key);
});
</script>
</body>
</html>
Keypress
keypress is an older keyboard event that only fired for character-producing keys and is now deprecated in most browsers -- keydown or keyup should be used for all new code instead.
Example: Keypress
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="field">
<script>
// keypress is deprecated; keydown/keyup are preferred for new code
$("#field").on("keypress", function(event) {
console.log("Character key pressed:", event.key);
});
</script>
</body>
</html>
Enter Key
Reading event.key inside a handler tells you exactly which key triggered the event, like Enter or ArrowUp, letting you write logic that responds to one specific key rather than any keystroke.
Example: Enter Key
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="field">
<script>
$("#field").on("keydown", function(event) {
if (event.key === "Enter") {
console.log("Enter was pressed");
}
});
</script>
</body>
</html>
Keyboard Shortcuts
Combining event.key checks with modifier flags like event.ctrlKey or event.shiftKey lets you build simple keyboard shortcuts, such as detecting Ctrl+S inside a form. Remembering to call event.preventDefault() is often necessary here too, since some key combinations have default browser behavior you need to override.
Example: Keyboard Shortcuts
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="field">
<script>
$("#field").on("keydown", function(event) {
if (event.ctrlKey && event.key === "s") {
event.preventDefault();
console.log("Ctrl+S shortcut triggered");
}
});
</script>
</body>
</html>
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: