I'm having trouble getting this image to move to the right can anyone help ive just started scripting and I am finding it very confusing.
<html>
<head>
</head>
<body style="margin:0px;">
<img id="tank" style="position:absolute;"src="tank.png"/>
<script type="text/javascript">
var change = document.getElementById('tank').style.left = '0';
while(change < 200)
{
change++;
}
</script>
</body>
</html>
There are many things wrong with that script...
First of all, you are attempting to set an integer as a CSS length - non-zero lengths require a unit, which you are not providing.
Second, primitive values are not passed by reference just because you want them to. Objects, however, are. So you could keep track of document.getElementById('tank').style
and change its left
property to move the image.
Third, the browser won't redraw the page while a script is running, meaning that if you got the script to move the image, it would immediately be at its end position (you won't even see it at the start position due to the script being run instantly).
I think that about covers everything you've done wrong. Now here's how to do it right.
(function() {
// don't leak variables into the global scope - think "variable = carbon dioxide"
var elem = document.getElementById('tank'), pos = 0,
timer = setInterval(function() {
pos++;
elem.style.left = pos+"px";
if( pos == 200) clearInterval(timer);
},25);
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With