jquery animation callback - how to pass parameters to callback
Solution 1
The problem is that x
is modified by the time the callback evaluates it. You need to create a separate closure for it:
for (x in LoopArr) {
$("#square").animate({ left: LoopArr[x][0][1] }, LoopArr[x][0][2],
(function (z) {
return function() {
alert (LoopArr[z][0][0]);
}
})(x));
}
I've renamed the parameter to z
here for clarification, you're passing x
as an argument to the function, which returns a function that makes use of the scoped z
variable, which stores the state of x
when it is passed.
Solution 2
Classic error in Javascript. Try this:
for (x in LoopArr) {
(function(x) {
$("#square").animate({ left: LoopArr[x][0][1] }, LoopArr[x][0][2], function() {
alert (LoopArr[x][0][0]);
});
})(x);
}
That makes sure that there's a distinct variable for each animation callback function created as the loop executes.
Related videos on Youtube
Hans
Updated on April 17, 2022Comments
-
Hans about 2 years
I´m building a jquery animation from a multidimensional array, and in the callback of each iteration i would like to use an element of the array. However somehow I always end up with last element of the array instead of all different elements.
html:
<div id="square" style="background-color: #33ff33; width: 100px; height: 100px; position: absolute; left: 100px;"></div>
javascript:
$(document).ready(function () { // Array with Label, Left pixels and Animation Lenght (ms) LoopArr = new Array( new Array(['Dog', 50, 500]), new Array(['Cat', 150, 5000]), new Array(['Cow', 200, 1500]) ); $('#square').click(function() { for (x in LoopArr) { $("#square").animate({ left: LoopArr[x][0][1] }, LoopArr[x][0][2], function() { alert (LoopArr[x][0][0]); }); } }); });
`
Current result: Cow, Cow, Cow
Desired result: Dog, Cat, Cow
How can I make sure the relevant array element is returned in the callback?