Tarida George
Tarida George

Reputation: 1303

Global variable doesn't change

I'm trying to get the dimensions of a image without to have it in DOM.

var myVariable;
$('<img src="http://www.skrenta.com/images/stackoverflow.jpg"/>').load(function(){
    myVariable = this.width;
}); 
console.log(myVariable);

Why console show that myVarible is undefined ?

Upvotes: 1

Views: 68

Answers (2)

Dave Newton
Dave Newton

Reputation: 160311

Image loading happens in separate requests.

myVariable will be set to the width at an arbitrary time in the future, almost always after that console.log call happens.

Upvotes: 1

alexmac
alexmac

Reputation: 19617

Your variable is undefined, because it's initialized after image is loading, or in another words: console.log calls early then function in load.

Upvotes: 3

Related Questions