2

I am trying to move my div element by having the body sense what key button I pressed, finding the right key symbol w, a, x, d, and then subtracting or adding from the css attributes of the html elements.

However it does not work and whenever I console log the elements or its attributes, nothing appears. The mover will not move.

var mover; 


function moveDivBlock(e){
    if ((e.keyCode == 69) ||(e.keyCode == 68)||(e.keyCode == 67)){//go right
        moveBlock(mover,10,0);}
    if ((e.keyCode == 81) ||(e.keyCode == 65)||(e.keyCode == 90)){//go left
        moveBlock(mover,-10,0);}
    if ((e.keyCode == 81) ||(e.keyCode == 87)||(e.keyCode == 69)){//go up
        moveBlock(mover,0,10);}
    if ((e.keyCode == 90) ||(e.keyCode == 88)||(e.keyCode == 67)){//go down
        moveBlock(mover,0,-10);}
}

function handleKeyDown(e) {
    moveDivBlock(e);
}


function moveBlock(elem, rightShift, upShift){
    var curLeft = parseInt(elem.style.left); 
    var curTop = parseInt(elem.style.top); 
    elem.style.left = (curLeft + rightShift) + "px"; 
    elem.style.top = (curTop - upShift) + "px"; 
}


window.onload=function(){
    mover=document.getElementById("mover");
}
    #mover{
        position:absolute;
        top:290px;
        left:130px;
    
        background-color:green;
        width:50px; 
        height:50px; 
        border:2px solid black;
    }
<body onkeydown="handleKeyDown(event);">
        <div id="mover"></div>
</body>
Strollas
  • 45
  • 4
  • Did you check, if `mover` is defined, when you call the `moveBlock` function? Also why do you subtract `upShift`, when you add `rightShift`? – Geshode May 27 '21 at 09:34
  • Because `elem.style` is not defined in `moveBlock` function, and the math gives `NaN`. You've to set the inline styles for the position in order to able to read the styles. – Teemu May 27 '21 at 09:34
  • check this https://stackoverflow.com/a/4951670/7750416 – Kashif May 27 '21 at 09:36

1 Answers1

3

The reason this was not working, elem.style.top returns inline style only, not style from css file. To get style from css file you need to use getComputedStyle(elem). Please try this


function moveBlock(elem, rightShift, upShift){
    var curLeft = parseInt(getComputedStyle(elem).left); 
    var curTop = parseInt(getComputedStyle(elem).top); 
    elem.style.left = (curLeft + rightShift) + "px"; 
    elem.style.top = (curTop - upShift) + "px"; 
}
Vivek Bani
  • 3,703
  • 1
  • 9
  • 18