0

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 answer Commented Jul 24, 2013 at 11:25

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

that was what i was looking for! but for some reason, there's another problem. for some reason, changing the margin for $(slide_image) only works for the very last image (which is #img3 in my case) so in other words, if i write $("#output").append(img_name,",") inside the function fn_get_natural_dim, it only shows "img3,img3,img3"

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.