Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move an image with javascript

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>
like image 384
user1482978 Avatar asked Oct 15 '25 13:10

user1482978


1 Answers

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);
})();
like image 150
Niet the Dark Absol Avatar answered Oct 18 '25 05:10

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!