Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I don't understand how my jQuery code is executed. how to achieve the required animation?

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading