Friday, January 2, 2009

Handling Javascript KeyPress

There are several reasons why you may want to capture the key press event in a browser window.
Getting the pressed key is easy in JavaScript, however different browsers use different ways for this. We will first see how this can on both Internet Explorer and Firefox.

Thanks to onkeyup we can easily handle the key pressing event in Internet Explorer. Here is the script we need to capture some of the keys on the keyboard:



<script type="text/javascript">

document.onkeyup = KeyCheck;


function KeyCheck(e)

{

var KeyID = (window.event) ? event.keyCode : e.keyCode;


switch(KeyID)

{

case 16:

document.Form1.KeyName.value = "Shift";

break;

case 17:

document.Form1.KeyName.value = "Ctrl";

break;

case 18:

document.Form1.KeyName.value = "Alt";

break;

case 19:

document.Form1.KeyName.value = "Pause";

break;

case 37:

document.Form1.KeyName.value = "Arrow Left";

break;

case 38:

document.Form1.KeyName.value = "Arrow Up";

break;

case 39:

document.Form1.KeyName.value = "Arrow Right";

break;

case 40:

document.Form1.KeyName.value = "Arrow Down";

break;
}

}
</script>


And the HTML to use with this is:

<form name="Form1">

<input type="text" name="KeyName" value="" />
</form>

No comments: