JQuery animation loop

I have a problem with the animation loop. There is an object that I want to move in a special way and do it in a loop. Are there any own options to do this? I have it:

$(function () { function runIt() { $('#div').show("slow"); $('#div').animate({"marginLeft":"300px"},8000); $('#div').animate({"marginLeft":"0px"},8000); $('#div').hide("slow", runIt); } runIt(); }); 

But it doesn’t seem very beautiful.

+6
source share
2 answers

This is how I do it. The only thing I would like to do is use the chain for more convenient code, and therefore the jquery object is not created every time.

 $(function () { function runIt() { $('#div').show("slow") .animate({"marginLeft":"300px"},8000) .animate({"marginLeft":"0px"},8000) .hide("slow", runIt); } runIt(); }); 
+16
source

This is the right way to queue animations. However, there are some things that can be done for your code to make it a little more enjoyable and beautiful:

  • Save the link to the selected item in a local variable to speed up execution (fewer requests made in the DOM)
  • Clean it by removing unnecessary quotes for object properties.
  • Size is measured in pixels by default, so we can use pure integers
  • You can replace the named function with the immediately called anonymous function, and then use arguments.callee as a callback

Here is an example demonstrating the above changes:

 $(function () { var element = $("#div"); (function(){ element .show("slow") .animate({ marginLeft: 300 }, 1000) .animate({ marginLeft: 0 }, 1000) .hide("slow", arguments.callee); }()); }); 

You can also do this in a more advanced way by creating your own plugin for using custom queues. I created a small script when I spoofed animation queues.

Read more about calling the function directly on the Ben "Cowboy" Alman blog .

+17
source

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


All Articles