1

I have a bunch of blocks that I'm trying to have move along a square 'track', like a train.

    var itemLoop = function(){
        $("li").each(function(getLeft, getTop) {
            getLeft = parseInt($(this).css('left'));
            getTop = parseInt($(this).css('top'));

            if (getTop > 0 && getLeft < 5) {
                $(this).css('top', (getTop - 5 ) + "px");
            } else if (getTop > 140) {
                $(this).css('left', (getLeft - 5) + "px");
            } else if (getLeft > 140) {
                $(this).css('top', (getTop + 5 ) + "px");
            } else {
                $(this).css('left', (getLeft + 5 ) + "px");
            }
        });
    }

setInterval(itemLoop, 100);

However, for the above, the blocks don't snake around the corners, but stay stuck together.

I thought maybe it was because the same getTop/Left value is being used for all the lis, but I'm not sure how else I could script this.

C_K
  • 1,243
  • 4
  • 18
  • 29

1 Answers1

2

You need to use the position() function rather than the css function. So instead of this:

getLeft = parseInt($(this).css('left'));
getTop = parseInt($(this).css('top'));

Do this:

var pos = $(this).position();

getLeft = parseInt(pos.left);
getTop = parseInt(pos.top);

Here's a working example: http://jsfiddle.net/judeosborn/rd2Ky/

Jude Osborn
  • 1,788
  • 16
  • 24
  • Also, it's a good idea to add the radix parameter to parseInt. So it should look more like getLeft = parseInt(pos.left, 10); Here's why: http://stackoverflow.com/questions/6611824/why-do-we-need-to-use-radix – Jude Osborn Jun 14 '13 at 06:43