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.
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.
you're looking for jquery .finish
http://api.jquery.com/finish/
$('.block').finish().css('top', '0').css('left', '0');
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.
to reset animation
$('.block').removeAttr('style'); //
$('.block').animate({
left: 50,
top: 50
});