0

I have a function here that checks if a picture has the dimensions of 100 by 100 pixels and if so returns true

function checkDims(url) {
    var valid = $("<img/>").attr("src", url).load(function() {
        s = { w: this.width, h: this.height };
        if (s.w == 100 && s.h == 100) {
            return true;
        }
        else {
            return false;
        }
    });
    return valid;
}

I want to set a variable called valid that checks by using a .load function to get the image size of a remote URL and I want it to return true or false accordingly. I know I'm setting it to a jQuery object but I want to get the results from the inner function.

I tried doing:

function checkDims(url) {
    var valid;
    $("<img/>").attr("src", url).load(function() {
        s = { w: this.width, h: this.height };
        if (s.w == 100 && s.h == 100) {
            valid = true;
        }
        else {
            valid = false;
        }
    });
    return valid;
}

But it gave me undefined as a value for valid when I called the checkDims function

so if I called

var s = checkDims(a_url)

. It would return

undefined

Community
  • 1
  • 1
Jebathon
  • 4,310
  • 14
  • 57
  • 108

1 Answers1

1

You need to break up your logic into two steps since this is an asynchronous call.

function checkDims(url, callback) {
    $("<img/>").attr("src", url).load(function() {
        callback (this.width == 100 && this.height == 100);   
    }).on("error") { callback(false); });
}

function nextStep(isValid) {
    alert("The image is " + ((isValid) ? "" : "not ") + "valid"
}

checkDims("foo.gif", nextStep);
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • So the nextStep function should return true or false? if I want to set var result = checkDims("foo.gif",nextStep)? – Jebathon Jun 09 '15 at 16:31
  • You can not return from this! It is impossible to return from an asynchronous call. You need to break your logic up so what ever you were doing after the call to checkDims needs to be in the function nextStep. – epascarello Jun 09 '15 at 17:15
  • So there is no way to set checkDims to the result of nextStep callback? – Jebathon Jun 09 '15 at 18:16