Javascript keydown: checking both for arrows and the minus sign, work-around for Firefox

428 views Asked by At

I am developing a web application with javascript in which

  • if the right arrow is pressed, we go to the next level.
  • if the minus sign is pressed, we reduce the difficulty.
  • if the space bar is pressed, we pause.

Because I want to check for arrows as well, I can't use the keypress event, so instead I'm using the keydown event. A simplified section of code (using jQuery) is the following.

$(document).keydown(dealWithKeyDown);
function dealWithKeyDown(evt) {
    if (evt.which == 39) // Right arrow.
        nextLevel();
    if (evt.which == 189) // Minus sign.
        reduceDifficulty();
    if (evt.which == 32) // Space.
        pause();
}

The problem I'm having now is that it doesn't work in Firefox. In FF the keycode for the minus sign is 173 instead of 189. (And there are more differences like that.) Can anyone suggest an easy/elegant work-around?

The easiest work-around I can think of is to use the 'evt.key' property, but 'evt.key' is undefined in Chrome, while for the space button IE gives 'evt.key == "Spacebar"' as true while Firefox gives 'evt.key == " "' as true. It's an inconsistency nightmare.

1

There are 1 answers

0
baao On BEST ANSWER

You can just check for the user agent and set the number accordingly, then use the var you took instead of the number!

var key = (/Firefox/i.test(navigator.userAgent)) ? 173 : 189 ;

then:

if (evt.which == key)

you can do this for all your numbers/possibilities