5

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;   
     }
}
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Trevor Rudolph
  • 1,055
  • 4
  • 18
  • 42

3 Answers3

10

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.

Raptor
  • 53,206
  • 45
  • 230
  • 366
1

You just need to handle the onkeydown event.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0
  1. correct your function to accept the event arg

    function KeyCheck(event) {
      var KeyID = event.keyCode;
      ...
    }
    
  2. if you want to use combination of keys, then use onkeypress event instead, push the keys into array and see if you have desired combination to follow.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
stac
  • 378
  • 1
  • 4
  • 10