I’m javascript newbie…please bear with me. Modified some jQuery animation code from w3c tutorial. I’m merely trying to dynamically show the local count (i) variable in the for loop that represents the # of iterations that have taken place for the set of (4) jQuery animation calls. I was expecting to see the text in the SPAN tag to dynamically change from 0 to 2 after each loop iteration. However, what actually takes place when button is clicked, is that “count:2” shows up immediately in span tag, then the animation takes place. This code executes (http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_animation) the same in the following browsers: Chrome, IE, FireFox, and Safari. What am i doing wrong and how can I get this to work?
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
for(i=0; i<3; i++)
{
$("div").animate({height:300},"slow"); //jQuery call 1
$("div").animate({width:300},"slow"); //jQuery call 2
$("div").animate({height:100},"slow"); //jQuery call 3
$("div").animate({width:100},"slow"); //jQuery call 4
document.getElementById("count").innerHTML="count: "+i; // JavaScript DOM call
}
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<br /><br />
<div style="background:#98bf21;height:100px;width:100px;position:relative">
<span id="count"></span>
</div>
</body>
</html>
__Original post above…new workking code below this line _____
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var i=0;
$("div").animate({height:300},"slow",function(){ document.getElementById ("count").innerHTML="jQuery Animation 1"; });
$(document).ready(function(){ $("button").click(function(){ myRecursiveFunction(i); }); });
function myRecursiveFunction(i)
{
document.getElementById("count").innerHTML="count: "+i;
$("div").animate({height:300},"slow");
$("div").animate({width:300},"slow");
$("div").animate({height:100},"slow");
$("div").animate({width:100},"slow",function(){
if(i < 10){myRecursiveFunction(++i);}
});
}
</script>
</head>
<body>
<button>Start Animation</button>
<br /><br />
<div style="background:#98bf21;height:100px;width:100px;position:relative">
<span id="count"></span>
</div>
</body>
</html>
animateis an asynchronous call.It returns immediately, and the animation happens in the background.
Your entire loop runs instantaneously.