Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1214 In the 'onKeyDown' or 'OnKeyPress' JavaScript 1.2 event handler, how can I get the keycode?

You are here: irt.org | FAQ | JavaScript | Event | Q1214 [ previous next ]

Try:

<script language="JavaScript"><!--
// if (document.layers) document.captureEvents(Event.KEYPRESS); // needed if you wish to cancel the key

document.onkeypress = keyhandler;

function keyhandler(e) {
    if (document.layers)
        Key = e.which;
    else
        Key = window.event.keyCode;
    if (Key != 0)
        alert("Key pressed! ASCII-value: " + Key);
}
//--></script>

In Netscape Navigator if you wish to capture the key press in a form field then you need to add the event handler to that too:

<form name="myForm">
<input type="text" name="myField">
</form>

<script language="JavaScript"><!--
// if (document.layers) document.captureEvents(Event.KEYPRESS); // needed if you wish to cancel the key

document.onkeypress = keyhandler;
document.myForm.myField.onkeypress = keyhandler;

function keyhandler(e) {
    if (document.layers)
        Key = e.which;
    else
        Key = window.event.keyCode;
    if (Key != 0)
        alert("Key pressed! ASCII-value: " + Key);
}
//--></script>

Feedback on 'Q1214 In the 'onKeyDown' or 'OnKeyPress' JavaScript 1.2 event handler, how can I get the keycode?'

©2018 Martin Webb