Wednesday, 3 December 2008

How do I handle or abort Function Key events (e.g. F1, F2,etc) in both IE and Firefox?

Run this page and you will be shown the keycode for the Function Key you pressed. In addition, any standard browser handlers (such as help prompts when F1 is pressed or Searches when F3 is pressed) will be aborted - so you can pass them to your app instead. See below:

<script type="text/javascript" language="javascript">
///Demo Script to display the function key that was pressed
///and abort any browser event e.g. F3 for IE find,
///F1 for IE help, F1 for Firefox Help
///Version Author Date Comment
///1.0 DDK 03 Dec 2008 Original Version for
/// Application Tender
/// Proof of concept
/// when users wanted 'green
/// screen' functionality
document.onkeydown = showDownAndAbortEvent;
//Stop F1 opening Help in IE
document.onhelp=function() {return false};
window.onhelp=function() {return false};

// decipher key down codes
function showDownAndAbortEvent(evt)
evt = (evt) ? evt : ((event) ? event : null);
if (evt) {
alert('keyCode:' + evt.keyCode + ';charcode' + evt.charCode + ';' ) ;
evt.preventDefault(); // disable default help in Firefox
catch (ex) {}
//Kill any intercepts for ie
window.event.cancelBubble = true;
window.event.returnValue = false;
window.event.keyCode = 0;
catch (ex) {}
return false;

1 comment:

Stivyx said...

Great script! Works for me (IE v6 & v7, Firefox v2 & v3, Ghrome).