0
votes

I have the following code:

function fn_get_natural_dim(){
    var width = this.width;
    var height = this.height;

    var ratiow = width/600;
    var ratioh = height/300;
    $("#output").append(img_name,",");

    if(ratiow>=ratioh)
        {
        height = height/ratiow;
        $(slide_image).css("width","600px");
        $(slide_image).css("height",height);
        var margin = (300-height)/2;
        $(slide_image).css("margin-top",margin);
        }
    else
        {
        width = width/ratioh;
        $(slide_image).css("width",width);
        $(slide_image).css("height","300px");
        var margin = (600-width)/2;
        $(slide_image).css("margin-left",margin);
        }
}
var max_count = $(".slider").children().length;
for(var count=1;count<=max_count;count++)
    {
    var count_string = count.toString();
    var img_name = "img" + count_string;
    var slide_image = document.getElementById(img_name);

    var img = new Image();
    img.onload = fn_get_natural_dim;
    img.src = $(slide_image).attr("src");
    }
});

For each image (i have three at the moment), im getting its natural dimensions so that i can calculate the margin necessary to fit a 600x300 div.

but i only works for the very last one, ie the third one. in other words, in the #output, it shows "img3,img3,img3," (called by $("#output").append(img_name,",");) how do i make it show "img1,img2,img3,"??

2
possible duplicate of function inside for loop (js/jquery)Barmar
You asked the exact same question less than an hour ago.Barmar
@Barmar it's not the exact same question - this code is (somewhat) fixed with the answer I gave to the previous question. Now the OP has a different problem.Alnitak
@Alnitak Yeah, I jumped the gun a little.Barmar

2 Answers

2
votes

You can do this:

    img.onload = (function(img_name, slide_image) {
        return function() {fn_get_natural_dim(img_name, slide_image); };
    })(img_name, slide_image);

and change fn_get_natural_dim to take the image name as a parameter:

function fn_get_natural_dim(img_name, slide_image) {

The above code captures each successive value of img_name in a closure variable.

-1
votes

Edit

As Barmar pointed out, this solution isn't exactly correct. I'll leave it up as it's a fairly common mistake and is important to note the difference between his solution and my own.


Pass img_name into your fn_get_natural_dim function:

function fn_get_natural_dim( img_name ) { ... }

Then call it like:

img.onload = function() { fn_get_natural_dim(img_name); };