How to decrease an HTML element’s X position in JavaScript?

I need to change an element’s X position every half-second. I’ve tried to decrease the amount of pixels, like this:

window.onload = function(){
  var star= document.getElementById("star");
  function moveStar() {
    star.style.left -= "100px"
  }
  setInterval(moveStar, 500)
}

I know this doesn’t work, but I don’t know what does. Any suggestions?


Thanks to @ScottMarcus for answering!

Answer

The CSS left property takes a string as a value (i.e. “100px”). You can’t do math with strings. You’ll need to convert the current left value to a number, do the math and then concatenate the “px” back on to the end.

Also, as long as you place your script just before the closing body tag and you don’t need access to external resources (like images), then you don’t need to set up an onload event handler and can just place your code there because by the time the parser reaches the closing body tag, all the HTML for the DOM will have been parsed in to memory.

var star= document.getElementById("star");

function moveStar() {
  // Get the integer portion of the left property
  // and do math on that and then add back the "px"
  // to set the new value. It's a best practice to
  // always specify the second optional argument to
  // parseInt, which is the radix (or the base numeral
  // system that you want used, so you don't accidentally
  // treat the initial value as a hex or octal. Here, we 
  // want base 10.
  leftNumber = parseInt(getComputedStyle(star).left, 10);
  star.style.left = (leftNumber - 50) + "px";
}
setInterval(moveStar, 500)
#star { width:100px; position:absolute; left:100%; height:50px; background-color:skyblue; }
<div id="star"></div>