onkeydown and onkeyup events don't work on Internet Explorer 8

Penta picture Penta · May 6, 2013 · Viewed 19.5k times · Source

My code works without problems on IE9/IE10, FF, Chrome and opera but on older Internet Explorer no Keyboard input is handled.

I have the following code for handling events. It should only fire when a new button is pressed.

lastEvent = void 0;

heldKeys = {};

window.onkeydown = function(event) {
if (lastEvent && lastEvent.keyCode === event.keyCode) {
  return;
}
lastEvent = event;
heldKeys[event.keyCode] = true;
switch (event.which) {
  case 80:
    return myamp.userInput("positiv");
  case 81:
    return myamp.userInput("negativ");
}
};

window.onkeyup = function(event) {
  lastEvent = null;
  return delete heldKeys[event.keyCode];
};

Answer

epascarello picture epascarello · May 6, 2013

You need to bind to the document, not window.

window.onkeyup = function(event) {
window.onkeydown = function(event) {

needs to be

document.onkeyup = function(event) {
document.onkeydown = function(event) {