Sitemap / Advertise

Information



Tags



Share

How to use the KeyboardEvent to return the character code

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement




Definition

If you are working on interactive pages for the user dashboard for your website, it would be a corroborating addition to return the Unicode character code of the key that is triggered. In this tutorial, I will show you how to manage that in JavaScript only, using the KeyboardEvent.

KeyboardEvent objects describe a user interaction with the keyboard; each event describes a single interaction between the user and a key (or combination of a key with modifier keys) on the keyboard. The event type (keydown, keypress, or keyup) identifies what kind of keyboard activity occurred.(1)

Code

Create an input element named text(id).

Add an event listener to the input element with the keypress property to detect whether a character is entered or not.

If there is a definable Unicode character code, change the charCode variable as the detected Unicode character code using logic statements.

Show the Unicode character code to the user.

<--------------JavaScript----------------->

document.getElementById("text").addEventListener("keypress", function(event){
var charCode = (event.charCode) ? event.charCode : "...";
document.getElementById("char").innerHTML = "Detected: " + charCode;
});

<--------------HTML----------------->

<input id="text" style="width:80%;" placeholder="Enter a character to see the Unicode..."></input>
<p id="char">...</p>

Result:

...

References

(1) https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent