Saturday, January 17, 2009

Capture Key Event in JavaScript

A friend of me wanted to control a hardware module that attached to a remote linux server using keyboard input in a client web page. She asked me how to do it. And I also didn't know :) We agreed to use JavaScript in client side and PHP on remote server. In the internet browser of the client computer, she didn't want to fill in and submit a form manually. That means key inputs must be captured directly and immediately sent to remote server to control the hardware accordingly.
After surfing for a while, a web page was found here about how to capture key inputs in JavaScript. Then we wrote a web page in PHP that sends key input directly. See the code that was written in "key.php".

<script language="JavaScript" type = "text/javascript">
document.onkeypress = DisplayMsg;
function DisplayMsg(key_event)
if (document.all) //Checks for IE 4.0 or later
document.form1.text1.value = String.fromCharCode(event.keyCode);
else if (document.getElementById) //checks for Netscape 6 or later
document.form1.text1.value = String.fromCharCode(key_event.which);
else if (document.layers) //Checks for Netscape 4
document.form1.text1.value = String.fromCharCode(key_event.which);
<title>Capture Key Pressed</title>
<div style="display:none">
<form name="form1" action="key.php" method=GET>
<input type = "text" name = "text1">
<div style="font-size: 40px; color:blue;">
echo "Received: ";
echo $_GET["text1"];

In this example, the problem in submitting the captured key is that the whole web page reloads everytime a key is pressed. It can be very slow when the page contains a lot of other contents. The better way is to use AJAX (Asynchronous JavaScript and XML) technique.

No comments:

Post a Comment

Comments are moderated and don't be surprised if your comment does not appear promptly.