Javascript when holding down arrow keys?

Trevor Rudolph picture Trevor Rudolph · Mar 10, 2011 · Viewed 16.7k times · Source

I have this script to trigger some javascript. But the script does not support holding down the arrow keys. How can I make this work when I hold the arrow keys.

document.onkeyup = KeyCheck;       
function KeyCheck()

{

var KeyID = event.keyCode;


switch(KeyID)

{

  case 37:

  right('img'); document.getElementById('img').src = 'guyl.png';

  break;

  case 38:

  up('img');

  break

  case 39:

  left('img'); document.getElementById('img').src = 'guyr.png';

  break;

  case 40:

  down('img');

  break;


 }

}

Answer

Raptor picture Raptor · Mar 10, 2011

should be:

document.onkeydown = KeyCheck;

onkeypress : invokes JavaScript code when a key is pressed

onkeydown : invokes JavaScript code when a key is held down (but not yet released)

onkeyup : invokes JavaScript code when a key is has been released after being pressed.