views:

484

answers:

2

I'm creating namespaced events with jquery. When I use the following function with code=112, a function, bool=false, everything works fine in FF and the F1 key submits to my function and the event does not bubble up to open the firefox help in a new tab.

function bindKeyFunc(code, func, bool){
    $(document).bind('keypress.' + code, function(e){
        var c = (e.keyCode ? e.keyCode : e.which);
        //console.log(c);
        if ( code == c) {
            //e.stopPropagation();
            //e.preventDefault();
            func();
            return bool;
        }
    });
}

In chrome and ie8 my event listener does not fire and the regular help occurs instead, even if I uncomment the stopPropagation and preventDefault calls.

Similarly, when I try to take over the <tab> key for my own purposes, it works splendidly in FF but my event doesn't fire in chrome or ie8 and the default action for the tab fires instead:

    $('input#manual-total').bind('keypress.dep', function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if ( code==9 ){
            $('div#formset').show();
            $(next).focus()[0].select();
            return false;
        }
    });
+1  A: 

You can not use keys F1-F12 cross-browser. Try this demo. http://jshotkeys.googlepages.com/test-static-01.html

Anatoliy
They have it working in chrome which I could live with. IE would be nice. Maybe I will just go with different keys. What about the tab issue?
skyl
Again, read the article I linked. No onkeypress in IE for tab, but onkeydown/up may work.
Craig Stuntz
It doesn't works for me (Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/4.0.203.2 Safari/532.0)
Anatoliy
my event listener doesn't work for you, Anatoly?
skyl
+1  A: 

Good luck. Mapping of special keys in browsers is a mess. In particular, IE certainly does not fire keypress events for function keys at all. onkeydown/up may work on IE, though. Many keys are handled incorrectly, in different ways by different browsers. I strongly doubt there is a cross-browser method of handling F1. Sorry; I know that's not the answer you wanted, but I believe it's the truth.

Do read the linked article, particularly the occasional warnings about "When I discovered that I decided not to risk my sanity by performing further punctuation character experiments." and the like. :)

Craig Stuntz
any thoughts on the chrome/ie tab-in-an-input corollary?
skyl
Since Chrome renders via WebKit, I would expect it to behave like Safari does in the chart I linked. I haven't tested, though. See also this: http://www.quirksmode.org/dom/events/keys.html
Craig Stuntz