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) {
alert('Enter key pressed');
}
else {
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. :)