I have the following javascript using jquery code:
function MakeAnimation(anim_times)
{
for (k=1; k<=anim_times; k++)
{
if ( $("#one").position().top >= 250 ) {
$("#one").animate({ top: '50px' }, 200, function() {});
} else {
$("#one").animate({ top: '+=50' }, 200, function() {});
}
}
}
and on the html body:
<button onclick="MakeAnimation(1);">step 1</button>
<button onclick="MakeAnimation(20);">step 20</button>
<div id="one" style="background-color:red; width:100px; height:100px; position:absolute; top:50px;"></div>
both buttons calling the same function, but when the function called with 20 times for for loop… the 5th line [ if ( $(“#one”).position().top >= 250 ) { ] does not work
any suggestions ?
thanks
Seems to be working as expected. I’ve created a fiddle for this.
Sorry, my bad! To answer AkisC’s question,
forloops are synchronous, butanimationsare asynchronous (ref. Wait for a jQueryanimation to complete within for loop).Thus, for the 2nd button, we always get ’50’ as the top value on every iteration and the
if ( $("#one").position().top >= 250 ) {is never executed.I’ve modified my fiddle with the new approach: http://jsfiddle.net/kayen/3SSeu/