0

I am trying to swap an image using jQuery but when I run the page, it seems the chase() method completes while the animation is still going. The idea is that the images are replaced with a flipped version so they appear to chase one another back and forth. However, the images appear facing to the left the entire time. The method seems to complete all at once, rather than showing each iteration.

<audio controls autoplay="false" onplay="chase()">
  <source src="Links/sillyChase.mp3" type="audio/mpeg" />
</audio>
<div id="dexter">
    <img id="dex" src="Images/dexterRight.jpg" width="170" height="120"/>
</div>
<div id="deedee">
     <img id="dee" src="Images/deedeeRight.jpg" width="170" height="120"/>
</div>
</div>

<script>
function chase(){
    for(var k=0;k<10;k++){ 
        $("#dex").attr("src","Images/dexterRight.jpg"); 
        $("#dee").attr("src","Images/deedeeRight.jpg"); 

        //moves images right  
        $("#dexter").animate({"left": "+=500px"},"slow"); 
        $("#deedee").animate({"left": "+=500px"},"slow"); 

        $("#dex").attr("src","Images/dexterLeft.jpg");
        $("#dee").attr("src","Images/deedeeLeft.jpg");  

        //moves images left 
        $("#dexter").animate({"left": "-=500px"},"slow"); 
        $("#deedee").animate({"left": "-=500px"},"slow"); 
    }
}
</script>
2
  • 3
    Use animate callback function or use promise() Commented Apr 8, 2013 at 17:38
  • Someone posted example code that helped me understand your comment, then deleted it....but I understand! Thank you so much! Commented Apr 8, 2013 at 17:53

1 Answer 1

1

Should work:

function chase(){
        for(var k=0;k<10;k++){ 
             $("#dexter,#deedee").promise().done(function() {
                   $("#dex").attr("src","Images/dexterRight.jpg"); 
                   $("#dee").attr("src","Images/deedeeRight.jpg");  
              });

              //moves images right  
              $("#dexter,#deedee").animate({"left": "+=500px"},"slow", function(){
                  $("#dex").attr("src","Images/dexterLeft.jpg");
                  $("#dee").attr("src","Images/deedeeLeft.jpg");
                  $("#dexter,#deedee").animate({"left": "-=500px"},"slow");
              });
        }

    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.