How to restart / reset jQuery animation

How do I reset animation in jquery? For instance:

CSS

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

JS:

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

If I do this:

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

the animation will stop. But how can I clear my position, start all over again? from point 0,0.

+5
source share
4 answers

When jQuery animates an element, it adds style-related information to the style attribute. If you need to reset an element to a basic style without jQuery css, just 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.

+7
source

are you looking for jquery .finish

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

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

You can use .stop() as you do, but add an argument to it to also clear the queue, and then reset the top and left positions with .css() :

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

.finish() also in the same category, but this puts all animations in their final state, which you do not want to do here. You just want to stop / clear the current animation (including any queues), and then reset the CSS properties back to their original state.

+1
source

to reset animation

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

Source: https://habr.com/ru/post/1200767/


All Articles