0

I've made a jsfiddle with all the code I use.

You can see a div that I want to move with keyboard arrow-keys. As you can see I can move object up / down / left / right using the keyboard. My problem is I want the object to move diagonally which means using up-and-down keys combined together.

I've surfed through SO but I've failed to find any example explaining this exact situation with arrow-keys handling. Can anyone please clarify.

Thanks in advance!

Here's my JS code below:

$(document).ready(function(){

var obj = $("#movetest")

$(window).on({
    keydown: function(e){
        if ( e.keyCode == 37 ){ move( obj, "left" ); }
        if ( e.keyCode == 38 ){ move( obj, "up" ); }
        if ( e.keyCode == 39 ){ move( obj, "right" ); }
        if ( e.keyCode == 40 ){ move( obj, "down" ); }
    }
})

});

function move(obj, dir){

    var curHPos = parseInt(obj.css("margin-left"),10),
        curVPos = parseInt(obj.css("margin-top"),10),
        newHPos = curHPos,
        newVPos = curVPos,
        diff = 10;

    if ( dir == "left" ) { newHPos = curHPos - diff; } else
    if ( dir == "right" ) { newHPos = curHPos + diff; } else
    if ( dir == "up" ) { newVPos = curVPos - diff; } else
    if ( dir == "down" ) {  newVPos = curVPos + diff; }

    obj.css({
        marginLeft: newHPos,
        marginTop: newVPos
    });
}
LoomyBear
  • 449
  • 2
  • 8
  • 19

1 Answers1

1

You need to take a look at this one: Can jQuery .keypress() detect more than one key at the same time?

In resume, you need to use the keydown and keyup events.

I ended it up in here: http://jsfiddle.net/GtG2p/2/

And I was basically doing this:

var keys = {};
var obj = $("#movetest");
$(document).ready(function(){
  $(document).on({
    keydown: function(e){
        keys[e.which] = true;
        throwKeys();
    },
    keyup: function(e){
        delete keys[e.which];
        throwKeys();
    }
  });
});

function throwKeys(){
  for (var i in keys) {
    if (!keys.hasOwnProperty(i)) continue;
    if ( i == 37 ){ move( obj, "left" ); }
    if ( i == 38 ){ move( obj, "up" ); }
    if ( i == 39 ){ move( obj, "right" ); }
    if ( i == 40 ){ move( obj, "down" ); }
  }
}
Community
  • 1
  • 1
hyunkeln
  • 429
  • 2
  • 9