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
});
}