0

I wrote a segment of code hoping to get key codes when the arrow keys are pressed.

document.onkeypress = function(e) {
    var keyCode = 0;
    e = e || window.event;
    keyCode = e.keyCode || e.which || e.charCode;
    console.log(keyCode);
};

I can get my key code in Firefox, but not in Chrome.

The keys is shown below in red box.

image of keyboard

How can I get my arrow key code?

Thanks.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
X.Zhang
  • 35
  • 4

2 Answers2

0

It would be helpful if you described what is happening in Chrome (is it throwing an error? is keyCode undefined?).

It may be because keyCode, charCode, and which are all deprecated. Instead, try using key

AJ Funk
  • 3,099
  • 1
  • 16
  • 18
0

Change onkeypress to onkeydown, and you'll get events with keyCode 37, 38, 39, and 40.

The keypress event is only fired for keys which have a character associated with them.