jqueryhtmlfirefoxkeycode

Key codes in different browsers? jQuery


All I have found about this is that there are inconsistencies among different web browsers when it comes to key codes.

I have the following code that runs fine when pressed enter in Safari, Opera and Chrome, but not in Firefox.

I use Firefox 9.0.1.

Here are two code snippets where the problem occurs:

1)

// Post something
$('#postDiv').on('keydown', '#posttext', function(e) {
    if ((e.keyCode == 13 || e.which == 13) && !event.shiftKey) {
        post($(this));
    }
});
// Comment on a post
$('.commenttext').live('keydown', function(e) {
    if ((e.keyCode == 13 || e.which == 13) && !event.shiftKey) {
        comment($(this));
    }
});

Both functions aren't even called.

I did some more testing only with e.which and noticed that it works when I leave out the && !event.shiftKey - apparently Firefox doesn't know that command. Is there any alternative to that? I would like the user to be able to hit Shift + Enter without submitting the post. I have already tried the condition if (e.which==13 && e.which!=16), but to no avail.

Solution

First of all thank you for all answers! Of course it had to be e.shiftKey, not event.shiftKey! Now it works in all browsers (the only one I haven't tried yet is Internet Explorer).


Solution

  • From http://api.jquery.com/event.which/

    The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.

    You shouldn't need to use e.keyCode and you may be running into issues where e.which != 13 but e.keyCode does. Have you verified the issue continues after removing the e.keyCode evaluation out of your control structures?