JSFiddle - React, Tailwind, and code Playground
HTML
<div id="movetest"></div>
CSS
#movetest{
background: salmon;
width: 20px;
height: 20px;
position: absolute;
top: 50%;
left: 50%;
}
JavaScript
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" ); }
}
}
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
});
}