Skip to content Skip to sidebar Skip to footer

How To Return A Variable Inside Img.onload = Function() In Jquery?

Let's get strait to my question: here is my code: function inside() { var gallery = $('#gallery'); var photo = $('#photo'); var width_mask = gallery.width(); //defin

Solution 1:

You cannot "return a value" from onload, because it's an asynchronous callback.

Well you can, but there is no point, since it's the browser who invokes the onload() callback, and is not interested in its return value.

Asynchronous = Will not be done immediately, but at some point in the future

Synchronous = Will be done immediately

Asynchronicity is dealt with using callbacks. A callback is a mechanism that works by passing a function to another function, so the callee function can inform the caller code about the work being completed, at some time in the future.

If the function worked synchronously, it could simply return the values without a callback. But the drawback would be that the code calling your function would have to wait for the image to be loaded from the server, which could take a long time and would make your program freeze for a long time if the response from the server takes a long time. You don't want to do that.

If you call the inside() function like this:

inside();

You can return a value (or anything) from the onload, as long as you do it asynchronously. You can do it by making these modifications:

functioninside(imageLoadedCb) {
    // ...

    img.onload = function () {
        // ...// notify the caller of inside() that image was loaded, with the values we want to returnimageLoadedCb(top_margin, left_margin);
    }
}

inside(
    // this is a function reference. it ends up in "imageLoadedCb" variable in "inside" functionfunction (top_margin, left_margin){
        // this code gets invoked from inside the onload() callbackconsole.log('top_margin= ' + top_margin + ' left_margin= ' + left_margin);
    }
);

Post a Comment for "How To Return A Variable Inside Img.onload = Function() In Jquery?"