1

Here is the code

https://jsfiddle.net/zdu1efrj/

$(document).ready( function() { 
    
    // start box animation code
    let animatedBox = $('.box');
    animatedBox.css('backgound', 'red');
     
    animatedBox.animate(
        {
            left: '500px', 
            height: '250px', 
            width: '250px'
        }, 1000);
    
    animatedBox.css('background', 'blue');

    animatedBox.animate(
        {
            top: '500px', 
            height: '100px', 
            width: '100px'
        }, 1000);

    // end box animation code 
});

I want the box in the animation to be red as long as it moves vertically then change its color to blue and moves down.

why isn't the code executed in sequence ?

why animatedBox.css('background', 'blue'); seems to be executed before the completion of

animatedBox.animate(
       {
           left: '500px', 
           height: '250px', 
           width: '250px'
       }, 1000);```
?
noorblue
  • 13
  • 3

1 Answers1

0

The issue here is because the animate() call is effectively asynchronous as the actions are placed in a queue and run at a later time. However the css() calls are not queued/async and so execute immediately.

To fix this use the callback argument of the animate() method so that you change the colour of the element after the first animation sequence completes:

animatedBox.animate({
  left: '500px',
  height: '250px',
  width: '250px'
}, 1000, function() {
  animatedBox.css('background', 'blue');  
});

However this can all be achieved much more effectively, and far more performantly, by using CSS alone:

body { position: relative; }

.box {
  position: absolute;
  left: 0;
  top: 0;
  width: 100px;
  height: 100px;
  position: absolute;
  background-color: red;
  animation: box-movement 2s forwards;
}

@keyframes box-movement {
  50% {
    left: 500px;
    top: 0;
    height: 250px;
    width: 250px;
    background-color: red;
  }
  100% {
    left: 500px;
    top: 500px;
    height: 100px;
    width: 100px;
    background-color: blue;
  }
}
<div class="box"></div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339