yzajoee
yzajoee

Reputation: 88

How can I return the variable which I get in the jQuery load function?

I was using the jQuery load function to get an img's real width like this

function getWidth(src){
    var _src = src;
    var pic_real_width;
    $("<img/>")
        .attr("src", _src)
        .load(function() {
            pic_real_width = this.width;
        });
    return pic_real_width;//it will be undefined
}

How can I get the true value of "pic_real_width"?

Upvotes: 0

Views: 68

Answers (2)

shu
shu

Reputation: 1956

Please try the following

function getWidth(src,widthfunction) {
        var _src = src;
        var pic_real_width;
        $("<img/>")
       .attr("src", _src)
       .load(function () {
           pic_real_width = this.width;
           GetPicWidth(pic_real_width);
       });

              }

    function GetPicWidth(width) {

        console.log(width);
        //do code with width

    }

    $(document).ready(function () {
        getWidth("//cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png?v=c78bd457575a", GetPicWidth);
     });

Upvotes: 0

Adam
Adam

Reputation: 5233

You'll need a callback:

function getWidth(src, callback){
    var _src = src;
    $("<img/>")
        .attr("src", _src)
        .load(function() {
            callback(this.width);
        });
}

getWidth('your_pic_src', function (pic_real_width) {
    console.log(pic_real_width);
});

Upvotes: 4

Related Questions