Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 833
Fede Avatar asked Aug 20 '14 15:08

Fede


3 Answers

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.

like image 151
Kami Avatar answered Sep 22 '22 07:09

Kami


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.

like image 40
jfriend00 Avatar answered Sep 26 '22 07:09

jfriend00


you're looking for jquery .finish

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

$('.block').finish().css('top', '0').css('left', '0');
like image 38
JF it Avatar answered Sep 24 '22 07:09

JF it