Atiris
Atiris

Reputation: 2703

jQuery change value after animation is done

This 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.

Upvotes: 1

Views: 3520

Answers (5)

parameciostudio
parameciostudio

Reputation: 590

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")}
                      });
}

Upvotes: 1

Atiris
Atiris

Reputation: 2703

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);

Upvotes: 0

Loktar
Loktar

Reputation: 35309

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.

Upvotes: 4

beeglebug
beeglebug

Reputation: 3542

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.

Upvotes: 0

Marcel Jackwerth
Marcel Jackwerth

Reputation: 54752

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.

Upvotes: 1

Related Questions