Keypress
In jQuery, keypress() method is a quick and easy way to add a key press listener to element(s).
I updated the HTML a little bit by adding a simple text input.
If I want to get a print message every time when I press the key in the input, I will write keypress() function:
$("input").keypress(function(){
console.log("You Pressed A Key!");})
So no matter what key I press, the console will print out the message right after I pressed the key.
If we want to listen for a key press only we hit the "Enter" key, we need to check the key code for enter key first.
The key code for "Enter" is 13. Therefore, we can write an if function in the keypress():
$("input").keypress(function(event){
if(event.which === 13) {
alert("You Hit Enter");}})
Comments
Post a Comment