jQuery Keyboard Events

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:
$(selector).keypress()

Example:

<!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>
Try Now

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:
  1. $(selector).keydown()

Example:

<!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> 
Try Now

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:
$(selector).keyup()

Example:

<!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>
Try Now 



ADVERTISEMENT
ADVERTISEMENT