1

this does not move the box when pressing the right and left arrow. please post in the comments if you can help.

window.addEventListener("keydown", testkey , false );
var el = document.getElementById("player");
//changes the x position by a value
function changex(num) {
    el.style.left = ((num + el.style.left) + "px");
}
//changes the y position by a value
function changey(num2) {
    el.style.top = ((num2 + el.style.top) + "px");
}
//sets x and y position of box
function setpos(x, y) {
    el.style.left = (x + "px");
    el.style.top = (y + "px");
}
//this returns the key that is pressed
function testkey(e) {
    if (e.keyCode == "37") {
        //left key
        changex(-10);
    }
    else if (e.keyCode == "39") {
        //right key
        changex(10);
    }
}
setpos(0,0);
Henry Redder
  • 27
  • 1
  • 11

2 Answers2

0

I see two issues:

First

You are adding numeric values to strings, which results in concatination. For example:
((num + el.style.left) + "px") is equivalent to 10 + 0px + px, which results in a string like 100pxpx. This is not a valid CSS value.

I suggest using parseInt to convert existing style values from strings to numbers:
el.style.left = parseInt(el.style.left) + num + "px";

For further reference, see Get a number for a style value WITHOUT the “px;” suffix.

Second

You'll need to position the element before you can use left,right,top, or bottom CSS definitions. The MDN notes that left (for example) only applies to "positioned elements".

Below, I've used position:absolute, but any valid position value will work.

For further reference, see css “left” not working.

Working Example

window.addEventListener("keydown", testkey, false);
var el = document.getElementById("player");

function changex(num) {
  el.style.left = parseInt(el.style.left) + num + "px";
}

function changey(num) {
  el.style.top = parseInt(el.style.top) + num + "px";
}

function setpos(x, y) {
  el.style.left = (x + "px");
  el.style.top = (y + "px");
}

function testkey(e) {
  switch (e.keyCode) {
    case 37: changex(-10); break;
    case 38: changey(-10); break;
    case 39: changex(10); break;
    case 40: changey(10); break;
    default:
  }

}

setpos(0, 0);
#player {
  position: absolute;
}
<div id="player">test</div>
Community
  • 1
  • 1
showdev
  • 28,454
  • 37
  • 55
  • 73
0

in your changex() and changey() functions, you're trying to do calculations between a number and a string. num comes in as a number but el.style.left is the string '0px'. put parseInt() around el.style.left like this and it works:

el.style.left = ((num + parseInt(el.style.left)) + "px");

Also make sure your player element has position:absolute applied via CSS.

HaulinOats
  • 3,628
  • 4
  • 21
  • 24