Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery animate loop

I have a problem with animate loop. There is an object i want to move in a special way and do it in loop. Are there any native options to make it? I have this:

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

But it seems not so pretty.

like image 487
Anton Avatar asked Jun 14 '11 13:06

Anton


1 Answers

That's the proper way to queue animations. However, there's some things that can be made to your code to make it a bit snappier and prettier:

  • Store a reference to the selected element in a local variable to speed up execution (less queries made to the DOM)
  • Clean it up by removing unnecessary quotes for object properties
  • Sizing is measured in pixels per default so we can use pure integers instead
  • The named function can be replaced with a immediately invoked anonymous function and then use arguments.callee as the callback

Here's an example showcasing 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 it in a more advanced way by creating your own plugin to use custom queues. I created a small fiddle a while back when I was fooling around with animation queues.

More about immediately invoked function expression can be read on Ben "Cowboy" Alman's blog.

like image 67
mekwall Avatar answered Oct 19 '22 23:10

mekwall