How to run .animate function in jQuery forever?

$(this).css("left","100px");

function endless(){
    $(this).animate({
        left:'-=100px',
    },{
        easing: "linear",
    duration: 5000,
    complete: function() {
        $(this).css('left','100px');
    endless();
        }
    });
};
endless();

This is what I tried, but using this approach, I cannot make things move. Im 'using jQuery 1.3.2. Any suggestions?

+5
source share
4 answers

You have options to animate incorrectly. It does not accept hash parameters, but only actual parameters for easing, duration, and callback. In addition, when using thisyou need to take care. It is better to pass it as an argument to an infinite function.

$(this).css("left","100px");

function endless(elem){
    $(elem).animate(
        { left:'-=100px' },
        "linear",
        5000,
        function() {
            $(elem).css('left','100px');
            endless(elem);
        }
     );
};
endless(this);
+3
source

In the callback you will need to call endless ().

function endless(item) {
  $(item).animate({"left": "-=100px"}, 5000, "linear", function(){
    $(item).css("left","100px");
    endless(item);
  });
}

endless($(".myBox"));
+2

$(this) , .

0

! , ,

I finally figured out how to switch it. with the following function, call endless (0) to stop and endless (1) to turn on the animation loop.

//loop animation forever
//args: takes 1 to loop, 0 to stop
function endless(loop)
{ 
  //animate forever
  if (loop==1)
  {
 $('#alink').animate(
  {'opacity':'toggle'}, 
  1000, 
   function () { endless(1) }
  ); 
  }
  //stop animation
  else
  {
 $('#alink').css('opacity',1).stop();
  }

}; 


//sample call
$('#alink').toggle(function(){ endless(1) },function(){ endless(0) });

thanx for source code!

0
source

All Articles