Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
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 ?

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

animatedBox.animate(
       {
           left: '500px', 
           height: '250px', 
           width: '250px'
       }, 1000);```
?
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!