1

I am trying to load an set of images and apply different styles to each one as the load in. When I run my code I only get the last set of styles passed in to be applied to all images.

For a group of images ids $foo load that image into its own box and then apply a height.

for ( var i = 0; i < $foo.length; i = i + 1 ) {
  $bar = i;
  $('.box'+[i]).load('/getimage/'+$foo[i]', function(){style($(this), $bar);}
}

function style(img, $bar){
 img.css('height', $bar);
}

Each image I format with the style function only gets set to height of last value of $bar.

I want to set the height to whatever the value of $bar is at the time that image is loaded.

1 Answer 1

4

You could use a closure to get the correct value on each iteration

for ( var i = 0; i < $foo.length; i = i + 1 ) {
    $bar = i;

    // closure to get correct value for i
    (function(index) {
        $('.box'+[index]).load('/getimage/'+$foo[index], function() {
           style($(this), index);
        });
    })(i);
}

function style(img, $bar){
    img.css('height', $bar);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.