开发者

jQuery change value after animation is done

This 开发者_C百科code down never call alert 'ane is true'.

It is possible to change local variable 'ane' from jQuery method "animate"?

In my code variable 'ane' is always false. I try this method for change of 'ane' value:

function anim() {
  var ane = false;
  $('#element').animate({left:'100px'}, 5000, function(){ ane = true; });
  while(!ane){}
  alert('ane is true');
}

This also does not work for me:

function anim() {
  var ane = false;
  var ant = function(){ ane = true; }
  $('#element').animate({left:'100px'}, 5000, ant);
  while(!ane){}
  alert('ane is true');
}

Thanks for reply.


Live Demo

function anim() {
  var ane = false;
    $('#element').animate({left:'100px'}, 5000, function(){
        ane = true;
        if(!$(this).is('animated')){
            alert(ane);
        }
    });
}

Once the animation completes you will be alerted.


JavaScript has only a single thread. If you use

while(!ane){}

jQuery can't run, thus not execute the animation, thus not complete the animation and set ane to true.


The answer of @Loktar is correct, but you could omit the condition

function anim() {
  var ane = false;
    $('#element').animate({left:'100px'}, 5000, function(){
        ane = true;
        // the animation is already finished
        // if(!$(this).is('animated')){
        //    alert(ane);
        //}
        alert(ane);

    });
}

because the function is called when the animation is actually finished.

Using the latest version of jQuery (>= 1.8) you can check if the animation is actually completed using the option done:

function anim() {
    var ane = false;
    $('#element').animate({width:'100px'}, 
                      {duration: 5000,
                       done: function () {alert("done")}
                      });
}


Try this:

function anim() {
  var ane = false;
  var ant = function(){ ane = true; }
  $('#element').animate({left:'100px'}, 5000, ant);
  setInterval(function(){ if(ane) { alert('ane is true'); } }, 100); 
}

ane should eventually be true, because this time the execution is not locked by the while loop.


Thanks to all. I used this to continue in the same executed function after animation:

// animation part
var ane = false; // check if animation end
$('#element').animate({left:'100px'}, 5000, function(){ane = true;});

// continue only if animation done
var fcb = setInterval(function(){ if(ane) {
  // continue executing function
  clearInterval(fcb); 
  // ...
  // nextCodePart();
  // ...
} }, 20);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜