How To Detect Keypress In JavaScript

Hi programmers… In this tutorial, you are going to learn how to detect keypress in JavaScript. In easy words, the script will detect when you press a key and show you which Key is pressed with the Unicode value of that key.

You can get a better idea if you read, How to find the Keycode in JavaScript ( Core JavaScript no jQuery )

JavaScript program to detect keypress

First, let’s create a text field first in HTML where you can enter your key or press a key.

<!DOCTYPE html>
<html>
<body>

<input type="text" onkeypress="detectkey(event)">

<p id="keystroke"></p>
</body>
</html>

We have used onkeypress DOM method here. We pass the detectkey() function. That means when someone will press key in the text area it will call the detectkey() function.

<p id="keystroke"></p>

This is the paragraph area where we gonna show the output of the script.

In this area, we will see the Unicode value of the key pressed as well as the real value known to normal users for better understanding.

For example, the value of A in Unicode is 65 but we the normal users know that this is capital A. It is more human understandable.

Let’s just create our function now.

<script type="text/javascript">

function detectkey(event) {
    var unicode = event.which || event.keyCode;
    document.getElementById("keystroke").innerHTML = "The pressed key was: " + String.fromCharCode(unicode) +"<br>The Unicode value is:"+ unicode;
}
</script>

 

Remember, passing an event as a parameter to the function is optional but sometimes it is useful for the handler function (here detectkey) to know about the event that happened.

Also Read,

Below is given the complete code in one place:

<!DOCTYPE html>
<html>
<body>

<input type="text" onkeypress="detectkey()">

<p id="keystroke"></p>

<script type="text/javascript">

function detectkey() {
    var unicode = event.which || event.keyCode;
    document.getElementById("keystroke").innerHTML = "The pressed key was: " + String.fromCharCode(unicode) +"<br>The Unicode value is:"+ unicode;
}
</script>

</body>
</html>

The unicode variable will store the Unicode variable of the key pressed. But in order to convert that Unicode value to non Unicode value we need to use this-

String.fromCharCode(unicode)

This can convert a Unicode code into character.

Suppose we have entered “B”

Below is what we see on our page for running the HTML file:

Detect keypress in JavaScript

In this text box, you can press key and the Unicode value will be displayed along with its character value.

Leave a Reply

Your email address will not be published. Required fields are marked *