keypress is kept here because older jQuery code and searches still refer to it. For new code, prefer keydown for keyboard commands and the input event for text-entry changes.
The historical keypress event was associated mainly with character-producing keys and was not dependable for keys such as arrows, Shift or Escape.
$( selector ).on( "keypress", function (event) {
// Legacy character-key event.
});
$( function () {
$( document ).on( "keypress", function (event) {
alert( "keypress: " + event.key );
});
});
The important practical difference is that keydown is the reliable choice for general keyboard handling, including non-character keys. keypress should not be the basis of new keyboard interfaces.
$( 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>
Open the comparison tutorial →
$( document ).on( "keydown", function (event) {
if ( event.key === "Escape" ) {
$( "#message" ).text( "Escape pressed" );
}
});
For text fields, listen to input when your goal is to react to the resulting text rather than a particular physical key.
keydown() · keyup() · Key-hold duration
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.