Function returns the value before Jquery Image load is executed

耗尽温柔 提交于 2019-12-02 04:38:22

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.

I had same issue while checking dimension of image as image loading is asynchronous . Also as said by @Abhinandan "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"

I used following approach. Hope it will help.

Set one extra attribute in image tag while on change of file like below

$('input[type=file]').on('change',function(){
    element = $(this);
    var files = this.files;
    var _URL = window.URL || window.webkitURL;
    var image, file;
    image = new Image();
    image.src = _URL.createObjectURL(files[0]);
        image.onload = function() {
            element.attr('uploadWidth',this.width);
            element.attr('uploadHeigth',this.width);
        }
    });

and now you can modify your function to below

$.validator.addMethod('checkDim', function (value, element, param) {     
    var image = new Image();
    var file = element.files[0];
    var _URL = window.URL || window.webkitURL;
    image.src = _URL.createObjectURL(file);
        if(element.uploadWidth== param[0] element.uploadHeigth== param[1]){ 
            return true;
        }
        else{            
            return false;
        }

}, 'Image dimension must be as specified');

It work for me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!