I have the following jQuery code:
$content.each(function(i) {
$body = $(this);
$(this).find('div.field-content')
.animate(
{
'top': 0
},
{
duration: 500,
complete: function () {
$(this).css('top', 0);
setBodyGradient($body);
}
}
);
});
In my case $content has 5 items. The problem seems to be that on the last iteration, the animation complete call back for $content.eq(0) has yet to fire, and when it does, the most recent version of $body is sent to setBodyGradient 5 times, rather than the version of $body at the point the callback was created.
I should say I’m running JQuery 1.4.4 on Drupal, so perhaps this is a bug fixed in the latest JQuery or is it a feature?
I know I can get around it by using $content.eq(i) instead, however I’m curious to know whether this is by design or buggy behaviour, and what the recommended method is? Should I always be looking to use $content.eq(i) ?
Do this instead:
Otherwise
$bodywill be a global variable and will resolve to the list item currently being processed. When the loop ends it will resolve to the last list item.Since the callbacks are executed after the loop is done
$bodywill always resolve to the last element in the list.Using
varmakes$bodya part of the scope chain of the function used by.each(). This means that$bodywill always resolve to the ‘correct’ list item.To see the difference, remove the
varkeyword immediately in front of$bodyfrom this fiddle and check your console.