So am trying to move an element with the directional pad on my keyboard. It moves, but once I switch direction (horizontal || vertical) it reestablishes the previous directions original location on program load. So if the element starts at margin-top
& margin-left
at 100px
once the element has been moved say horizontally leaving coordinates now as MT = 100px
& ML = 150px
once I switch to vertical the elements ML becomes 100. This is not what I want to have happen, what I'd like is for the elements ML & MT to be representative of it's prior manipulations. Move from 100&100 to 150&100 and then to 150&150. Plus no library's, straight JS.
var spacePos = 5;
var spaceNeg = -5;
var output;
var marginLeft =1;
var marginTop =1;
function init(){
output = document.getElementById('output');
document.onkeydown = updateKeys;
}
updateKeys = function(e){
currentKey = e.keyCode;
output.innerHTML = "current key: " + currentKey;
if (currentKey=='39') {
marginLeft = marginLeft + spacePos;
document.getElementById('blockB').style='margin-left:' + marginLeft +'px';
}
else if (currentKey=='37') {
marginLeft = marginLeft + spaceNeg;
document.getElementById('blockB').style='margin-left:' + marginLeft +'px';
}
else if (currentKey=='38') {
marginTop = marginTop + spaceNeg;
document.getElementById('blockB').style='margin-top:' + marginTop +'px';
}
else if (currentKey=='40') {
marginTop = marginTop + spacePos;
document.getElementById('blockB').style='margin-top:' + marginTop +'px';
}
}
K_LEFT = 37;
K_RIGHT = 39;
K_UP = 38;
K_DOWN = 40;
#blockB{
width:10px;
height:10px;
margin-top:100px;
margin-left:100px;
position:absolute;
background-color: blue;
}
<body onload='init()'>
<div id='output'> </div>
<div id='blockB'> </div>
</body>