Set the background color of an <input> field when a keyboard key is pressed down:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script>/*from www . ja v a 2 s. c o m*/ <script> $(document).ready(function(){ $("input").keydown(function(){ $("input").css("background-color", "yellow"); }); $("input").keyup(function(){ $("input").css("background-color", "pink"); }); }); </script> </head> <body> Enter your name: <input type="text"> <p>Enter your name in the input field above. It will change background color on keydown and keyup.</p> </body> </html>
The keydown event occurs when a keyboard key is pressed down.
The keydown()
method triggers the keydown event.
The keydown()
method can run a function when a keydown event occurs.
We can use the event.which property to return which keyboard key was pressed.
Trigger the keydown event for the selected elements:
$(selector).keydown()
Attach a function to the keydown event:
$(selector).keydown(function)
Parameter | Optional | Description |
---|---|---|
function | Optional. | function to run when the keydown event is triggered |