bigbluetaxi
bigbluetaxi

Reputation: 71

Why does jQuery .animate callback occur before the animation?

Why is the callback on this .animate function happening, before the animation?

Refer: http://jsfiddle.net/93Qyq/7/

This is the Javascript portion:

$('#clickButton').click(function() {
  $('.spanClass').animate({
    left: '+=200'
  }, 500, positionReset());
});

function positionReset(){
    alert('complete!');
   $('.spanClass').animate({'left':'-=200'})
}

This is the HTML:

<div class="divClass">
<span id="a" class="spanClass">A</span>
<span id="b" class="spanClass">B</span>
<span id="c" class="spanClass">C</span>
</div>
<br>
<div id="clickButton">CLICK BUTTON</div><br>​

Upvotes: 3

Views: 242

Answers (4)

GajendraSinghParihar
GajendraSinghParihar

Reputation: 9131

positionReset() will call the function as its a function call. You need to pass the function object to the animate callback as positionReset

See THE DEMO

$('#clickButton').click(function() {
  $('.spanClass').animate({
    left: '+=200'
  }, 500, positionReset);
});

Upvotes: 1

AGB
AGB

Reputation: 2448

Because you are invoking the function by putting brackets after it. To pass a reference to the function you just use it's name, without the brackets. e.g.

$('#clickButton').click(function() {
  $('.spanClass').animate({
    left: '+=200'
  }, 500, positionReset);
});

Upvotes: 1

A. Wolff
A. Wolff

Reputation: 74420

Should be:

$('#clickButton').click(function() {
  $('.spanClass').animate({
    left: '+=200'
  }, 500, positionReset); //not positionReset() or you will autocall callback function
});

Upvotes: 4

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262919

That's because you're not passing your function to animate() -- you're calling it, and passing the value it returns (which is not a function, and is subsequently ignored by the framework).

You have to remove the parentheses after your function:

$('.spanClass').animate({
    left: '+=200'
}, 500, positionReset);  // No parentheses.

Instead of:

$('.spanClass').animate({
    left: '+=200'
}, 500, positionReset());

Upvotes: 6

Related Questions