javascript - nav controls for a for loop animation -


i have simple animation fading in , out each list item in unordered list. html markup follows:

<ul>   <li>first par</li>   <li>second par</li>   <li>third par</li> </ul>  <div></div> 

the empty div contain buttons nav controls dynamically via jquery.

the script follows:

<script>  var ul = $('ul'), li = $('ul li'), li_length = li.length, div = $('div');  //hides list items li.hide();  function play (eq){   eq = (eq===undefined) ? 0 : eq;     for(i=eq, d=0; i<li_length; i++, d+=3000){     li.eq(i).delay(d).fadein(1000).delay(1000).fadeout(1000);   } }  //this dynamically appends nav buttons in div li.each(function(i){   div.append('<button> '+ + '</button>'); })  //the normal animation going through each list item, fading in , out play();  var btn = $('div button');  //each button when clicked should animate corresponding list item (fadein , out), next  li.each(function(i){    btn.eq(i).click(function(){      li.stop(true, true);      li.hide();      play(i);    }) })  </script> 

when play() runs, job. when click nav button, e.g. 2nd list item playing click button 1 (essentially calls play(1)), loop (from play()) still seems playing though have stopped animation of list items using .stop(). result overlapping animations. noob , clueless how approach there no overlap in animations. can help?

delay continue run regardless of stopping current animation:

the .delay() method best delaying between queued jquery effects. because limited—it doesn't, example, offer way cancel delay—.delay() not replacement javascript's native settimeout function, may more appropriate use cases.

instead of delay should use settimeout , cancel inside click handler:

var timeoutid = settimeout(function() { [fadein/fadeout] }, delayduration); 

then click handler:

btn.eq(i).click(function() {     ...     cleartimeout(timeoutid); }); 

the way have play setup run, you'd need set , cancel timeout each li animation.

amended

using settimeout, of code rewritten follows:

function play (eq){     var         eq = eq || 0,         i, d;       for(i=eq, d=0; i<li_length; i++, d+=3000){          // store timeoutid returned settimeout on li         li.data('timeoutid', settimeout(function() {                 li.eq(i).fadein(1000).delay(1000).fadeout(1000);             }, d)         );     } } 

then in click handler:

li.each(function(i){     btn.eq(i).click(function(){         li.stop(true, true);         li.hide();          // grab timeoutid , clear         cleartimeout(parseint(li.data('timeoutid'), 10));          play(i);     }); }); 

you may need additional call settimeout delay between fadein/fadeout, point above code.


Comments