Henry Redder Henry Redder - 6 months ago 17
Javascript Question

Element not changing position when updating the style top and left

This code below should change the position of the element but fails to do so.

//variables
var p1 = document.getElementById("player");
var px = 10;
var py = 10;

//@variables

//functions

function start() {
setInterval(update, 100);
}

function update() {
p1.style.left = (px + "px");
p1.style.top = (py + "px");
px = px + 10;
py = py + 10;
}

//@functions

//start
start();
//@start`


my html is:

<html>
<head>
<title> jumpy </title>

<style type="text/css">
#player {
position: absolute;
background-color: white;
width: 100px;
height: 100px;
border-radius: 50%;
}
#body {
background-color: black;
}

</style>

</head>
<body id="body">
<script src="jumpy.js"> </script>
<div id="player"> </div>
</body>
</html>



Even though the position is absolute it still does not work.
I have seen the answer at the bottom but it did not fix my problem.

Answer

Your problem is that your script is run before your element is created. As a result document.getElementById("player"); returns nothing (the element is not loaded yet).

Move the script tag at the end of your body, or wrap your code in

window.addEventListener("load", function(){
  // Your code.
});

Appart from this, your code works fine (except that requestAnimationFrame should be used to create animation with js, not setInterval). If it does not, the problem is somewhere else.

window.addEventListener("load", function(){

  //variables
  var p1 = document.getElementById("player");
  var px = 10;
  var py = 10;

  //@variables

  //functions

  function start() {
    setInterval(update, 100);
  }

  function update() {
    p1.style.left = (px + "px");
    p1.style.top = (py + "px");
    px = px + 10;
    py = py + 10;
  }

  //@functions

  //start
  start();
  //@start`

});
#player {
  position: absolute;
  background-color: white;
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
body {
  background-color: black;
}
<div id="player"></div>

Comments