jQuery Animation : changing an animation parameter mid-animation

animation, jquery

Solution

One option is to use the `step` function mentioned in the jQuery `animate` function (API) to check a condition while the animation is running.

Example JSFiddle : http://jsfiddle.net/GweLA/13/

JS

var myTargetWidth = 500;

$(document).ready(function(){
    $('.sample').animate( { "width" : myTargetWidth },{
        duration : 5000,      
        step: function(now, fx) {
            if($(this).width() > 200){
              myTargetWidth = 300;
              $(this).stop().animate({ "width" : myTargetWidth },1000);
            }
        }
    });
});

CSS

.sample{
    width:20px;
    height:100px;
    background-color:#cccccc;    
}

HTML

<div class="sample">
   width is supposed to be animated till 500 but it stops at 300
</div>

Solution 2:

After some research I found that we can modify the `start` and `end` properties of `fx` parameter passed to the step function to control the animation. This kind of smoothens the animation, but not a very tidy way of doing it though.

Example JSFiddle : http://jsfiddle.net/GweLA/57/

JS

var myTargetWidth = 500;
var isExecuted = false;
$(document).ready(function(){
    $('.sample').animate( { "width" : myTargetWidth },{
        duration : 5000,
        queue : false,
        step: function(now, fx) {
                 //So that fx.start and fx.end is set only once                
                if($(this).width() > 200 && $(this).width() < 203){
                    if(!isExecuted){
                        fx.start = now-65;
                        fx.end = 300;
                    }
                    isExecuted = true;
                }
              }
    });
}); 

Problem

Suppose you had a long animation where you were changing the `width`: ``` var myTargetWidth = 500; $(el).animate( { "width" : myTargetWidth }, 5000 ); ``` The animation is asynchronous so your code continues . . . a couple seconds later you decide to change the target `width` to `300` . . . the animation is still running at this point . . . How would I change targetWidth to a different value on the running animation?

Original source