jQuery Keyboard Events With Examples
.keydown()
When we press a down key on the keyboard, then keydown event happens.
The keydown()
method in jQuery either initiates a keydown event or attaches a function to run when one occurs.
Example of key-down keyboard event in jQuery
When a keyboard key is pressed, change the background colour of an input field:
$("input").keydown(function(){
$("input").css("background-color", "yellow");
});
.keypress()
The keypress()
method in jQuery either initiates a keypress event or attaches a function to run when one happens.
The keypress is quite similar to the keydown event. It performs when a key is pressed. When a button is pressed, the event occurs.
Not all keys trigger the keypress event, though (e.g., ALT, CTRL, SHIFT, ESC). To double-check these keys, use the keydown()
method.
Example of keypress keyboard event in jQuery
Count the number of key pushes in an input field:
$("input").keypress(function(){
$("span").text(i += 1);
});
.keyup()
The keyup event in jQuery occurs when we press a keyboard key.
The jQuery keyup()
method either triggers a keyup event or adds a function that will run when one happens.
Example of keyup keyboard event in jQuery
When a keyboard key is released, change the background colour of an input field:
$("input").keyup(function(){
$("input").css("background-color", "pink");
});