Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop a jQuery div animation?

I’m trying to implement a jQuery function with an infinite loop to animate a div. I can’t figure out how to do it. This is my code:

$(document).ready(function () {
    $('#divers').animate({
        'margin-top': '90px'
    }, 6000).animate({
        'margin-top': '40px'
    }, 6000);
});
like image 746
Eduardo Gustavo Salazar Avatar asked Nov 13 '12 19:11

Eduardo Gustavo Salazar


5 Answers

put the code that does the full animation into a function, then pass that function as the callback param to the last animation. Something like...

$(document).ready(function() {   
    function animateDivers() {
        $('#divers').animate(
            {'margin-top':'90px'}
            ,6000
        )
        .animate(
            {'margin-top':'40px'}
            ,6000
            ,animateDivers //callback the function, to restart animation cycle
        ); 
    }

    animateDivers(); //call, to start the animation
}); 
like image 91
madlee Avatar answered Nov 19 '22 00:11

madlee


$(document).ready(function() {
    function ani() {
        $('#divers').animate({
               'margin-top':'90px'
            },6000).animate({
               'margin-top':'40px'
           },6000, ani); //call the function again in the callback
        }); 
    }); 
    ani();
}); 
like image 28
adeneo Avatar answered Nov 19 '22 00:11

adeneo


use the .animate() callback to 'recall' your function:

jsBin demo

$(function() {
  
  
  function loop(){
   $('#divers')
     .animate({marginTop:90},6000)
     .animate({marginTop:40},6000, loop); // callback
  }
  
  loop(); // call this wherever you want


}); 
like image 39
Roko C. Buljan Avatar answered Nov 19 '22 01:11

Roko C. Buljan


Using setInterval is the way to go. Too much recursion will just get you "Stack Overflow" :-) "Uncaught RangeError: Maximum call stack size exceeded"

like image 21
eyal_katz Avatar answered Nov 18 '22 23:11

eyal_katz


The animate() function has an option to take a function to call when the animation ends. You could just do the same call, and voila.

like image 1
thatidiotguy Avatar answered Nov 19 '22 01:11

thatidiotguy