Why is my finished jQuery function being called before the animation finishes?
<button onclick="$.MyObject.add('wrapper');">Add</button>
Somewhere in the code I did:
$.MyObject= new MyUberObject();
then in my add function I specify my call and call the animation and pass its callback.
function MyUberObject(data) {
...
this.add = function(name, index) {
var callback = function(n,i) {
$.MyObject.addDiv(n, i);
alert("wtf");
}(name, index);
$("#outerWrapper").animate(
{
"width": "+=200px",
},
{
duration : "fast",
easing: "linear",
complete: callback
}
);
...
}
However, the alert appears immediately after the button is clicked, after I cleared the alert, the animation will go ... I've tried many different ways to specify the callback and also tried using a delay and calling it elsewhere ... so far not.
+3
source to share
3 answers
var callback = function(n,i) {
$.MyObject.addDiv(n, i);
alert("wtf");
}(name, index);
You are calling the callback here, so you are calling it.
Try this, I think the name and index must exist because of the closure.
function MyUberObject(data) {
...
this.add = function(name, index) {
var callback = function() {
$.MyObject.addDiv(name, index);
alert("wtf");
};
$("#outerWrapper").animate(
{
"width": "+=200px",
},
{
duration : "fast",
easing: "linear",
complete: callback
}
);
...
}
if not, then you can add the name and index to the outer shell:
function MyUberObject(data) {
...
this.add = function(name, index) {
var callback = function() {
$.MyObject.addDiv($(this).data("props").name, $(this).data("props").index);
alert("wtf");
};
$("#outerWrapper").data("props", {name : name, index : index};
$("#outerWrapper").animate(
{
"width": "+=200px",
},
{
duration : "fast",
easing: "linear",
complete: callback
}
);
...
}
or maybe even easier ...
function MyUberObject(data) {
...
this.add = function(name, index) {
var callback = function(n, i) {
$.MyObject.addDiv(n, i);
alert("wtf");
};
$("#outerWrapper").animate(
{
"width": "+=200px",
},
{
duration : "fast",
easing: "linear",
complete: function(){callback(name, index);}
}
);
...
}
+5
source to share