Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q233 Is it possible to trap control key presses?

irt.org | Knowledge Base | JavaScript | Misc | Q233 [ previous next ]

Q233 Is it possible to trap control key presses?

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.


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.