Search code examples
javascriptjqueryangularjsjquery-uijquery-file-upload

Function returns the value before Jquery Image load is executed


if (DataService.Validation(file)) {
    //angularjs call to api controller
};    

//DataService
Validation: function (file) {
    var Url =   URL.createObjectURL(file);
    var img = new Image();

    $(img).load(function () {
        var imgwidth = this.width;
        var imgheight = this.height;
        if (imgheight  > 400) {
            viewModel.ErrorMessage = 'The Image height cannot be more then 400 px.';
            return false;
        }
    });

    img.src = Url;

    if (file == null) {
        viewModel.ErrorMessage = 'Please select a file to upload.';
        return false;
    }

    if (viewModel.Name == null) {
        viewModel.ErrorMessage = 'Name is a required field.';
        return false;
    }

    return true;
}

The above validation function is completing the execution and returning true without the code inside img load function is checked..It means tht even if the image is greater then 400px the validation returns true as the code inside load runs after a long time once the whole Jquery ajax call is sent to api controller.. What I am trying to achieve is that the Validation should not return the value until the code inside the image load is executed.


Solution

  • The behaviour is correct as your function will return with 'true' value always. IMG load function will execute only after your image is completely loaded by the browser and since its asynchronous your function will not wait for it to execute. Also if you want to check the width/height of image being loaded, use naturalWidth/naturalHeight as this will give the right values and not the one assigned to the image by css.

    What you can do is inside image-load function,you can call your function with true/false value as parameter.