iJade
iJade

Reputation: 23811

Trigger image onload using javascript or jquery

My situation is that i need to check the size of an image using javascript and then execute a piece of code depending on its width.Here is my code

        var width, height;
        var img = new Image();
        img.src = "pool.jpg";
        img.onload = function () {
            width = this.width;
            height = this.height;
            console.log(width);
        }
        console.log(width);

        if (width > 0) {
            console.log('in condition check');
            //Some code to be executed
        }
        //Some other code to be executed which cannot be put in the onload portion

the issue is that the img.onload portion works only after the below code has finished execution.Is there any way to trigger the img.onload function and go in a synchronous way of code execution.

Upvotes: 1

Views: 5944

Answers (2)

You'll need to wait for the callback, then you can pass the result to another function:

var width, height;
    var img = new Image();
    img.src = "http://kushsrivastava.files.wordpress.com/2012/11/test.gif";
    img.onload = function () {
        width = this.width;
        height = this.height;
        console.log(width);
        if (width > 0) {
            console.log('in condition check');
            //Some code to be executed
            haveFun(width);
        }
    }
    var haveFun = function(w) {
        console.log('Im having fun with ' + w );
    }

Here's a jsfiddle with a lil' sample.

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382464

No, you can't make your code wait until the external task (usually involving a server) has finished execution.

You have to put your code in the callback (or in a function called from the callback) :

   img.onload = function () {
        width = this.width;
        height = this.height;
        console.log(width);
        if (width > 0) {
           console.log('in condition check');
           //Some code to be executed
        }
    }

To build JavaScript applications, you must learn to deal with event-based programming, where most of your code act upon events, be them user actions or asynchronous task completions.

(technically there is a way but don't use it)

Upvotes: 1

Related Questions