How To Detect Keypress In Javascript

By Saruque Ahamed Mollick

Hi programmers, In this tutorial, you are going to learn how to detect keypress in JavaScript. In easy words, the script will 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 )

Detect keypress in JavaScript Easily

So, here I am gonna create a text field first where you can enter your key or press key.

<!DOCTYPE html>
<html>
<body>

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

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

We have used onkeypress here. 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 example, the value of A in Unicode is 65 but we the normal users know that this is capital A.

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 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,

Consistently Move an Element with Arrow Keys in JavaScript

How to Access HTML Form Elements in JavaScript  Tutorial

So our whole code will be like this

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

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”

Output:

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 *