Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, how do I tell if a user is pressing two keys at the same time?

In Javascript, how do I tell if a user is pressing two keys at the same time?

For example, I have drawn a circle in the middle of the screen. I want to move it up while the user holds down the up arrow and right while the user holds down the right arrow. That part works easy. If user holds both the up and right arrows, I want to move the circle diagonally, up and to the right.

It doesn't look like this possible with basic Javascript event handling, but surely someone has figured out a work around/hack/improvement.

like image 547
Chad DeShon Avatar asked Jan 07 '10 04:01

Chad DeShon


1 Answers

Here is what you need to do conceptually (I guess this is called pseudo code):

Start with something like this:

var PIXEL_DELTA  = 10; // Distance to move in pixels

var leftPressed  = 0,
    upPressed    = 0,
    downPressed  = 0,
    rightPressed = 0;

Then on every keydown event, test if it the key pressed is left, up, etc and turn its variable from 0 to PIXEL_DELTA.

On every keyup event, run the same test and turn the correct variable back to 0.

Then, in your moving code (real code): (This code adapted from Crescent Fresh's awesome example):

function move() {
  var dot = document.getElementById('dot'),
      deltaX = rightPressed - leftPressed,
      deltaY = downPressed - upPressed;

  if(deltaX) {
    dot.style.left = (parseInt(dot.style.left, 10) || 0) + deltaX + 'px';
  }

  if (deltaY) {
    dot.style.top = (parseInt(dot.style.top, 10) || 0) + deltaY + 'px';
  }
}

The browser will (should) fire a separate keydown/keyup event for each key, even if they are "simultaneously" pressed.

Working Example

Crescent Fresh put together a full example on JSBin. Be sure to visit the editable version as well to play with the code.

like image 69
Doug Neiner Avatar answered Oct 19 '22 08:10

Doug Neiner