0

I have problem with width and height.

My function:

function testImageSize(testSrc) {

    var imageTestLink = "";
    var link = testSrc.attr("src");

    link = link.replace("/thumbs/", "/images/");
    imageTestLink = link.replace(".thumb", "");

    var theImage = new Image();
    theImage.src = imageTestLink;

    console.log(imageTestLink);

    var rw = theImage.width;
    var rh = theImage.height;

    console.log(rw, rh);

}

My problem is that, when I run this function imagesTestLink returns always correct link to image. But rw and rh sometimes return 0 0 values in console. Can someone help me solve this problem? I have read alot of topics but i dont find my answer.

Regards, Fantazy

Fantazy
  • 37
  • 8

1 Answers1

1

The problem is that the image may not be loaded before the function ends. You'll need to use a callback in order to deal with that...

var rw;
var rh;

function testImageSize(testSrc, callback) {
    var imageTestLink = "";
    var link = testSrc.attr("src");

    link = link.replace("/thumbs/", "/images/");
    imageTestLink = link.replace(".thumb", "");

    var theImage = new Image();

    //  create an event handler that runs when the image has loaded
    $(theImage).on("load", function() {
        rw = theImage.width;
        rh = theImage.height;
        callback();
    });

    console.log(imageTestLink);

    theImage.src = imageTestLink;
}

testImageSize("/thumbs/thumbnail.jpg", function() {
    // this function will only be executed once the image has loaded
    console.log(rw, rh);
});

Basically, you create a function that you want to run when the image has loaded and you've got the size, and you pass that into testImageSize. That loads the image and once that's completed it gets the size and then calls the function you passed in.

Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67