Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prototype observe event problem in Opera

I'm using Prototype and doing Event.observe on window.document.

I'm catching enter (keyCode 13) and alt+f (altKey && keyCode=70).

My code is working super with firefox, IE and chrome. With Opera no. Enter is catched, but only if my focus is not in any text input. Alt+F is not working at all.

Is it bug in Prototype or I need to do something 'extra' on Opera in order to go on? As i said, in all other browser my code works....

like image 705
стривігор Avatar asked Nov 05 '22 03:11

стривігор


1 Answers

Firstly, the following is a helpful resource: http://unixpapa.com/js/key.html

Secondly, you should know there is a difference between keydown (or keyup) and keypress. keypress does not typically allow modifier keys, though it does allow some in Opera like control. Better to use keydown for cross-browser consistency.

I get keyCode === 13 in Opera 11.10 no matter whether the textbox is entered or not, and no matter whether using Prototype like this:

Event.observe(document, 'keydown', function (e) {
    alert(e.charCode+'::'+e.keyCode);
});

or using the native method directly (using attachEvent for IE):

if (document.addEventListener) {
    document.addEventListener('keydown', function (e) {
        alert(e.charCode+'::'+e.keyCode);
    }, false);
}
else { // IE
    document.attachEvent('onkeypress', function (e) {
        alert(e.charCode+'::'+e.keyCode);
    });
}

However, alt is indeed not detected inside a textbox unless combined with a control or function key (though that doesn't work in Chrome or IE). This may be because Windows uses alt to give access to the applications menu bar.

You could try using control key and using preventDefault() (to avoid default behaviors like ctrl-f doing a page find) though this might annoy your users who might not want their browser behaviors disabled for your page.

like image 141
Brett Zamir Avatar answered Nov 09 '22 14:11

Brett Zamir