how to reset a jquery animation to start over?

被刻印的时光 ゝ 提交于 2019-12-05 03:30:37

I had an animation that was keeping the position each time the code ran. To fix it I used:

function(){ $('.target').removeAttr('style'); }

so my code was something like:

$('#target').animate({
  opacity: 'toggle',
  top: '+=100',
  }, 1000, function() {
  $('#target').removeAttr('style'); 
});
nsordk

For jQuery you can use .finish(), and before that, to reset you need a few parameters to the .stop() method.

$(element).stop(true, true);

https://api.jquery.com/stop/

$(element).stop(), then re-run your animation.

There is no easy answer since it all depends on what you've done, what state you need to reset, what UI elements need to be reset and so on. I guess you have to build your own reset method that sets all things to their initial state or... you could take the easy path and just reload the page.

Thank you for patient answers. Both are right:

  • in case of one animation the stop method works.

  • in case of multiple chained animations - sorry, there is no easy way. Reload if you want a short but not so elegant solution. To do it properly - learn javascript to build the logical chain of functions. You can't run long with just jQuery.

bdurao

I do it this way: (not sure if it's entirely right, though)

$(element).stop();
$(element).clearQueue();
$(element).delay(20).animate({ ... });

Try .finish().
Example (try spamming the button):

$('button').on('click', function(event) {
  $("div").finish();
  $("div").fadeOut(1000);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!