Bartek Kosa
Bartek Kosa

Reputation: 842

How to refresh/reload CSS style in loop?

I have this function which should to change <div> left position in loop making it to look like it is moving. But instead it just jumps to the end position.

function anim (id, left) {
    $('#k' + id).css('left', parseInt($('#k' + id).css('left')) + 1);
    if(parseInt($('#k' + id).css('left')) == left){
        return;
    }
   setTimeout(anim(id, left), 100);
}

I want it to look like jQuery animate but without using jQuery animate function. What I miss?

EDIT working example: http://jsfiddle.net/h7MuB/21/

Upvotes: 1

Views: 266

Answers (2)

harpo
harpo

Reputation: 43168

You've misunderstood the argument to setTimeout.

setTimeout(anim(id, left), 100);

should be

setTimeout(function() { anim(id, left); }, 100);

This is a common mistake. You want to pass a function to setTimeout. What you were doing is calling the function, and passing its return value (which, since you don't have a return statement, is undefined).

That's why the animation "jumped": because you were calling the next step immediately, and not really using the timeout.

Note that you can use a function name with no function () {} wrapper, if you do not need to pass arguments. If you want to pass arguments, you need to create a closure as above.

Upvotes: 3

Bryan
Bryan

Reputation: 3494

If I had to guess it's probably doing what you want it to do, but it's working too fast for it to actually appear animated, you should try delaying your script in each iteration to get a visual animation. Check out this function... SetTimeOut()

Upvotes: 0

Related Questions