Dylan Thepiguy
Dylan Thepiguy

Reputation: 43

javascript - unable to change object position

var img = new Image();
img.className = "block";
img.src = "http://db.tt/xCGgJN48";
img.style.left = x + "px";
img.style.top = y + "px";
var array = [];
array.push(img);
document.getElementById("mydiv").appendChild(array[0]);
//imagine some delay here
array[0].style.left = (array[0].style.left + 10) + "px";

i cant get the image to move. btw thats not the actual code, the last line of code is whats not moving it and i have other bits of code in between. whats wrong with it??

Upvotes: 2

Views: 349

Answers (1)

MattDiamant
MattDiamant

Reputation: 8771

This line of code is where the issue is:

(array[0].style.left + 10) + "px";

array[0].style.left is returning something like 100px. So, adding 10 to that will be 100px10, and then adding px to that will be 100px10px. What you need to do is use parseInt to covert the 100px to 100, and then adding 10 will be 110, and adding px to that will give you the correct 110px.

array[0].style.left = parseInt(array[0].style.left) + 10 + "px";

Upvotes: 2

Related Questions