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

Q233 Is it possible to trap control key presses?

You are here: irt.org | FAQ | JavaScript | Misc | Q233 [ previous next ]

I've been able to trap Ctrl+[letter], although some combinations are reserved for the browsers. The first free letter in both Netscape Navigator 4 and Internet Explorer 4 is 'E':

<head>
<script language="JavaScript1.2"><!--
function netscapeKeyPress(e) {
     var prefix = '';
     if (e.modifiers & Event.CONTROL_MASK) prefix = 'c';
     if (e.modifiers & Event.ALT_MASK) prefix += 'a';  // does not work !
     if (e.modifiers & Event.SHIFT_MASK) prefix += 's';
     document.test.output.value += prefix + e.which + ' ';
     if (prefix + e.which == 'c5')
         alert('Ctrl and E pressed');
}

function microsoftKeyPress() {
    var prefix = '';
    if (window.event.shiftKey) prefix = 's';
    if (window.event.ctrlKey) prefix += 'c';
    if (window.event.altKey) prefix += 'a';
    document.test.output.value += prefix + window.event.keyCode + ' ';
    if (prefix + window.event.keyCode == 'c5')
       alert('Ctrl and E pressed');
}

if (navigator.appName == 'Netscape') {
    window.captureEvents(Event.KEYPRESS);
    window.onKeyPress = netscapeKeyPress;
}
//--></script>

</head>

<body onKeyPress="microsoftKeyPress()">

<form name="test"><textarea name="output" cols="40" rows="20" wrap="virtual"></textarea>

<script language="JavaScript"><!--
document.test.output.value = '';
//--></script>

</body>

The netscapeKeyPress() function was amended after a useful suggestion from Martin Honnen.

©2018 Martin Webb