views:

165

answers:

2

I'm writing javascript code for a web emulator containing function keys. The user is able to press keyboard function keys to process something in the emulator, I used stopPropagation and preventDefault javascript function to stop/cancel browsers invoking their function key shortcut (e.g. F1 will invoke Firefox to open its help page) and the code works fine under Firefox and Chrome. But Opera didn't work, Opera invokes both my function and launches Opera help page. I'm using latest Opera 10.5 here. Can anyone help ?

this code is in FireFox javascript handle and this is attached in main body HTML onkeydown event:

function KeyHandler(ev)
{
   if(112==ev.keyCode) {InvokeF1();return CancelKey(ev);}
   if(113==ev.keyCode) {InvokeF2();return CancelKey(ev);}
   ...
}

function CancelKey(ev)
{
    ev.stopPropagation();
    ev.preventDefault();
}

IE used different code for CancelKey, which use ev.CancelBubble = true and ev.returnValue = false.

A: 

I guess you are using onkeydown event. It doesn't give you the required thing in Opera. But works fine in IE and Firefox. So you have to use onkeypress event in opera. So you should have a separate code base for opera in your javascript which can handle Opera function keys.

Multiplexer
The `keydown` event does work in Opera. You just cannot prevent the browser's default action with that event.
Tim Down
Thanks for your comment. I communicated it wrongly.
Multiplexer
A: 

To prevent the default action of a keypress in Opera, you need to do it in the keypress event. The following is adapted from my answer to this similar question:

var cancelKeypress = false;

document.onkeydown = function(evt) {
    evt = evt || window.event;
    cancelKeypress = /^(112|113)$/.test("" + evt.keyCode);
    if (cancelKeypress) {
        return false;
    }
};

/* For Opera */
document.onkeypress = function(evt) {
    if (cancelKeypress) {
        return false;
    }
};
Tim Down