Introduction: Hello Guys, “Welcome back” Today i am here with another one new great article. In this article I will explain about how to find the KeyCode of key that will be press by the user on Keyboard using JavaScript.
Join our Channel on Whtsapp and Telagram for All Updates
Code for HTML Page
Implementation: On the HTML page there i will place two Textboxes control for entering the text by the user to find the keycode with the id named txt_input_1 and txt_input_2 respectively. On the first textbox I will use onkeyup use event handler and on the second box I will user onkeydown use event handler
keyup
<input id="txt_input_1" type="text" onkeyup="GetKeyCode(event)"/>
keydown
<input id=" txt_input_2" type="text" onkeydown="GetKeyCode(event)"/>
Explanation
Working of ASCII Code on keyup and keydown events in different browsers
1. Browser named Mozilla Firefox has all ASCII codes of all the keys in the event named event.keyCode, it means whenever it is used on keyup and keydown event handler, you will get the keyCode of the pressed or released key.
But when you call it on keypress event it stores the ASCII codes of all keys that produce a character that is visibile like A - Z, 0 - 9, and other character keys in charCode while keyCode has ASCII codes of all non-character keys like BACKSPACE, SHIFT, CTRL, etc.
2. Browser named Internet Explorer (IE), Edge, Chrome and Safari has ASCII code of only character keys when called on keypress event.
3. Browser named Opera you will get ASCII code of the all the keys in the event.keyCode event.
So in case when you want to get ASCII codes on keypress event you will need to use the following function.
JavaScript function
<script type = "text/javascript">
function GetKeyCode(evt)
{
var keyCode;
if(evt.keyCode > 0)
{
keyCode = evt.keyCode;
}
else if(typeof(evt.charCode) != "undefined")
{
keyCode = evt.charCode;
}
alert("You pressed : " + keyCode);
}
</script>
Here i am giving the complete code for HTML page. You can copy and paste the code on your HTML page and enjoy the execution of the code.
<!DOCTYPE HTML>
<html>
<head >
<title></title>
</head>
<body>
<input id="txt_input_1" type="text" onkeyup="GetKeyCode(event)" />
<input id="txt_input_2" type="text" onkeydown="GetKeyCode(event)" />
<script type="text/javascript">
function GetKeyCode(evt) {
var keyCode;
if (evt.keyCode > 0) {
keyCode = evt.keyCode;
}
else if (typeof (evt.charCode) != "undefined") {
keyCode = evt.charCode;
}
alert("You pressed : " + keyCode);
}
</script>
</body>
</html>
Conclusion: In above code, I explained that how to find the KeyCode of key that will be press by the user on Keyboard using JavaScript. This code is very helpful for every developer. Bye Bye and take care of you Developers. We will come back shortly with the new article.
Regards
Using Asp.net
No comments:
Post a Comment