Tip to Detect Key Press through JavaScript and jQuery






4.50/5 (6 votes)
Detect type of key press through JavaScript and jQuery
Introduction
Sometimes, we are in a situation when we are required to find out which key is pressed through code. Below is the sample code for getting key press using client side script (JavaScript and jQuery):
Using JavaScript
<script type="text/javascript">
document.onkeydown = testKeyEvent;
document.onkeypress = testKeyEvent
document.onkeyup = testKeyEvent;
function testKeyEvent(e) {
if (e.keyCode == 13) //We are using Enter key press event for test purpose.
{
alert('Enter key pressed');
}
else //If any other button pressed.
{
alert('Not Enter key pressed');
}
}
</script>
Using jQuery
<script>
$(function () {
$(document).on('keyup keydown keypress', function (event) {
if (event.keyCode == 13) {
alert("Enter key pressed");
}
else {
alert("Not Enter key pressed");
}
});
});
</script>
Use the above code and play with key press. :)