JQuery keyboard event handler click and hold

I want to create a simple event handler for the game, here is my code

     $(document).keydown(function(e){
      switch(e.keyCode){
        case 65: //left (a)

          console.log('left');
          break;

        case 68: //right (d)

          console.log('right');
          break;

      }
    });

the problem is that if I press and hold the key, after a few seconds it works several times. how can i prevent this behavior? I run my code on Google Chrome

+4
source share
2 answers

This is a key repetition. You can defeat it if you want, remembering that you already know that the key does not work:

// A map to remember in
var keysdown = {};

// keydown handler
$(document).keydown(function(e){

  // Do we already know it down?
  if (keysdown[e.keyCode]) {
      // Ignore it
      return;
  }

  // Remember it down
  keysdown[e.keyCode] = true;

  // Do our thing
  switch(e.keyCode){
    case 65: //left (a)

      console.log('left');
      break;

    case 68: //right (d)

      console.log('right');
      break;

  }
});

// keyup handler
$(document).keyup(function(e){
  // Remove this key from the map
  delete keysdown[e.keyCode];
});

Side note: I think that when you use jQuery, it e.whichis a more reliable property, since it normalizes for you jQuery .

+7
var keyPressed = false;

$(document).on('keydown', function(e) {
  var key;
  if (keyPressed === false) {
    keyPressed = true;
    key = String.fromCharCode(e.keyCode);

    //this is where you map your key
    if (key === 'X') {
      console.log(key);
      //or some other code
    }
  }
  $(this).on('keyup', function() {
    if (keyPressed === true) {
      keyPressed = false;
      console.log('Key no longer held down');
      //or some other code
    }
  });
});
+2

All Articles