2

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

Jonas G. Drange
  • 8,749
  • 2
  • 27
  • 38
DanH
  • 5,498
  • 4
  • 49
  • 72

1 Answers1

3

Do this instead:

$content.each(function(i) {
     var $body = $(this);  

Otherwise $body will 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 $body will always resolve to the last element in the list.

Using var makes $body a part of the scope chain of the function used by .each(). This means that $body will always resolve to the 'correct' list item.

To see the difference, remove the var keyword immediately in front of $body from this fiddle and check your console.

Jonas G. Drange
  • 8,749
  • 2
  • 27
  • 38
  • Oh yes thank makes sense, it's always the basic stuff that gets me :) – DanH Aug 09 '12 at 13:04
  • I would not say this is basic stuff, but glad I could help. Take a look at http://stackoverflow.com/questions/500431/javascript-variable-scope for better understanding. – Jonas G. Drange Aug 09 '12 at 13:10