Caleb Roberts
Caleb Roberts

Reputation: 11

Javascript - Move an image to the right

This is a function thats supposed to move an image slowly to the right, it isnt working... what did i mess up?

<script type="text/javascript">
var userWidth = window.screen.width;
function moveRight(id, speed) {
    var pp = document.getElementById(id);
    var right = parseInt(pp.style.left);
    var tim = setTimeout("moveRight(id, speed)",50);
    right = right+speed;  // move
    if (right > window.screen.height / 2)
    {
        right=0;
        pp.style.left = right+"px";
    }
}
</script>

Upvotes: 1

Views: 3867

Answers (1)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107528

Looks like id and speed aren't getting passed into moveRight(). When they're in the string as you have them they won't get evaluated. Have a look at this, it seems to do the trick. I stripped it down a little.

<div id="test" style="width: 50px; height: 50px; left: 0px; background-color: #000; position: absolute;">&nbsp;</div>

<script type="text/javascript">

    function moveRight(id, speed) {

        var pp = document.getElementById(id);
        var right = parseInt(pp.style.left) || 0;

        right += speed;  // move
        pp.style.left = right + "px";

        var move = setTimeout(function() {
            moveRight(id, speed);
        }, 50);

    }

    moveRight('test', 1);

</script>

A jsfiddle to play with. You can tweak it to your liking.

Upvotes: 4

Related Questions