Fede
Fede

Reputation: 1716

How to restart/reset Jquery animation

How can i reset an animation in jquery ? For example:

CSS

.block {
    position:absolute;
    top: 0;
    left: 0;
}

JS:

$('.block').animate({
    left: 50,
    top: 50
});

If I do :

$('.block').stop();

the animation will stop. But how can i clear the position, to start over ? from point 0,0.

Upvotes: 10

Views: 23529

Answers (4)

ayed abboushi
ayed abboushi

Reputation: 71

to reset animation

$('.block').removeAttr('style'); //
$('.block').animate({
    left: 50,
    top: 50
});

Upvotes: -1

Kami
Kami

Reputation: 19407

When jQuery is animating an element, it adds the style related information in the style attribute. If you need to reset the element to it's base style without the jQuery css, simply remove this attribute at the end of the animation - See .animate() on jQuery API.

$('.block').animate({
    left: 50,
    top: 50
}, 'slow', function () { $(this).removeAttr('style'); });

The callback function will remove the style attribute and reset the element at the end of the animation.

Upvotes: 19

jfriend00
jfriend00

Reputation: 707328

You can use .stop() like you are doing, but add an argument to it to also clear the queue and then reset your top and left positions using .css():

$('.block').stop(true).css({top: 0, left: 0});

.finish() is also in this same category, but that puts all the animations at their final state which isn't something you want to do here. You just want to stop/clear the current animations (including any queued ones) and then reset the CSS properties back to your starting state.

Upvotes: 3

JF it
JF it

Reputation: 2403

you're looking for jquery .finish

http://api.jquery.com/finish/

$('.block').finish().css('top', '0').css('left', '0');

Upvotes: 1

Related Questions