jQuery keypress
jQuery keypress method triggers with key press event of the javascript. Since this event varies across browsers, this is not covered in any official specification. This event triggers only for the focused element. This can vary across different browsers.
jQuery keypress method syntax
- keypress(): This jQuery keypress method is used without any arguments.
- keypress(handler): This jQuery keypress method attaches a function to be executed when the keypress event is fired.
jQuery keypress example
Following example demonstrates the use of jQuery keypress method.
jquery-keypress.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<!DOCTYPE html> <html> <head> <title>jQuery keypress event example</title> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script> $(document).ready(function(){ $("input:text").keyup(function(){ $("input:text").css("background-color","red"); }); $("input:text").keypress(function(){ $("input:text").css("background-color","yellow"); }); //reset jQuery keydown css $("input:reset").click(function(){ $("input:text").css("background-color","white"); }); }); </script> </head> <body> <h3>jQuery keypress example</h3> Enter anything: <input type="text"> <input type="reset"> <br><br> Type something above, background colour will change to yellow on key press. <br><br> Click on Reset button to try again. </body> </html> |
In above example, when the key is pressed, keypress() method is triggered which in turn executes the function that changes the background colour to yellow.
Below screencast shows above jQuery keypress event example in action.