When the user press or release a key on the keyboard then the keyboard event fires.
Here are some jQuery methods to handle the keyboard events.
1) The keypress() Method:
When a keyboard button is pressed down then the jQuery keypress () event occurs and that keypess () event executes the keypress() method or attach a function to run.
Syntax:
1 2 3 |
$(selector).keypress() |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> i = 0; $(document).ready(function(){ $("input").keypress(function(){ $("span").text(i += 1); }); }); </script> </head> <body> Please enter your name: <input type="text"> <p>Keypresses: <span>0</span></p> </body> </html> |
2) The keydown() Method
When a keyboard key is pressed down then keydown event occurs and that keydown event triggers the keydown() method or attaches a function to run.
Syntax:
- $(selector).keydown()
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("input").keydown(function(){ $("input").css("background-color", "red"); }); $("input").keyup(function(){ $("input").css("background-color", "blue"); }); }); </script> </head> <body> Please enter your name: <input type="text"> <p> Please enter your name in the above input field. It will change the background color on keyup and keydown.</p> </body> </html> |
3) The keyup() Method
When a keyboard button is released after pressing then the jQuery keyup() event occurs and that event executes or attach a function to run.
Syntax:
1 2 3 |
$(selector).keyup() |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("input").keydown(function(){ $("input").css("background-color", "red"); }); $("input").keyup(function(){ $("input").css("background-color", "blue"); }); }); </script> </head> <body> Please enter your name: <input type="text"> <p> Please enter your name in the above input field. It will change the background color on keyup or keydown.</p> </body> </html> |