0
votes

I call a function inside a for loop, but the function doesn't seem to work properly

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

    var ratiow = width/600;
    var ratioh = height/300;
    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");
    }
});

in my HTML, i have several images with id #img1, #img2, and so on. For each of them, I'm getting its natural dimensions by calling a new Image(), then adjusting its size to fit a 600x300 div. The above is inside the function fn_get_natural_dim()

when i call this function inside the for loop, it doesnt work. specifically, the width and the height variables turn out to be zero. at first i thought the "this" in the function no longer pointed to the img variable, so i switched "this" to "img" but it still does not work.

1
img.onload = fn_get_natural_dim(); will use the returned result of this function which seems to be 'undefined'. See @Alnitak's answerA. Wolff

1 Answers

1
votes

You're calling fn_get_natural_dim when you should just be passing a reference to it:

img.onload = fn_get_natural_dim;

There might be other problems too, but this one's the killer.