The keydown event fires when a key is pressed down. It works for character keys as well as non-printing keys such as Escape, Shift, arrow keys and function keys.
For current jQuery code, bind it with .on("keydown", handler).
$( selector ).on( "keydown", function (event) {
// A key was pressed down.
});
$( function () {
$( document ).on( "keydown", function (event) {
alert( "Key pressed: " + event.key );
});
});
Open the original keydown demo →
$( document ).on( "keydown", function (event) {
$( "#d1" ).text(
"Key: " + event.key + " | Code: " + event.code
);
});
event.key describes the key value, while event.code identifies the physical key location. For new code, these are more useful than numeric key codes.
keydown works for control and navigation keys. The older keypress event was mainly associated with character entry and is now a legacy browser event, so new interfaces should normally use keydown and/or input.
$( document ).on( "keydown", function (event) {
$( "#d1" ).text( "keydown: " + event.key );
});
$( document ).on( "keypress", function (event) {
$( "#d2" ).text( "keypress: " + event.key );
});
<div id="d1"></div>
<div id="d2"></div>
Compare keydown and keypress →
keyup() runs when the key is released. The keypress legacy reference explains the older character-key event. See key-hold duration for an example that combines keydown and keyup.
Legacy key-number demo is retained for reference; the modern tutorial is event.which and its replacement.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.