L Lassale L Lassale - 5 months ago 7
jQuery Question

JavaScript Trying to move a image with events

I'm trying to move a image with a js script but it doesnt work, the console dont show anything.



<html>

<body onload ="do_timer()">
<img id="the_image" src="https://s15-us2.ixquick.com/cgi-bin/serveimage?url=http:%2F%2Fstatic.allbackgrounds.com%2Fbg%2Forange.jpg&sp=fe8f01b8441f1d048c52dbd3721287a2" style="position: absolute; left:0px;">
</body>
<script>
function do_timer() {
var the_timer, x_position = 0
, the_image;
the_image = document.getElementById("the_image");
x_position++;
the_image.style.left = x_position;
the_timer = setTimeout(do_timer, 50);
}
</script>

</html>




Answer

Working fiddle.

  1. You should place the tag </body> after the end of script (after tag </script>).

  2. The variables should be defined before outside of the function so you will not reset them in every call :

    var the_timer, x_position = 0, the_image;
    
    function do_timer() {
    ....
    
  3. Set the image one time outside of the function :

    the_image = document.getElementById("the_image");
    
  4. You need to add the unit sign px after the position value x_position so it will be :

    the_image.style.left = x_position+'px';
    
  5. Better if you could separate the CSS code and avoid the inline style :

    #the_image{
       left: 0px;
       position: absolute;
    }
    

FULL CODE :

<body onload ="do_timer()"> 
    <img id="the_image" src="http://image.flaticon.com/teams/1-freepik.jpg">
    <script>
        var the_timer, x_position = 0, the_image=document.getElementById("the_image");

        function do_timer() {
          x_position++;
          the_image.style.left = x_position+'px';
          the_timer = setTimeout(do_timer, 50);
        }
    </script>
</body>

Hope this helps.

var the_timer, x_position = 0, the_image=document.getElementById("the_image");

function do_timer() {
  x_position++;
  the_image.style.left = x_position+'px';
  the_timer = setTimeout(do_timer, 50);
}
#the_image{
  left: 0px;
  position: absolute;
}
<body onload ="do_timer()"> 
  <img id="the_image" src="http://image.flaticon.com/teams/1-freepik.jpg">
</body>