A. Z.
A. Z.

Reputation: 736

How to get image size from a file with jQuery?

I want to get a width from a file to use it as a variable. Trying that:

iconOS_img = new Image();
iconOS_img.src = '/details/images/icon.png';
var iconOS_img_width = iconOS_img.width;

alert(iconOS_img_width);

However, it returns 0.

Upvotes: 1

Views: 111

Answers (2)

Amadan
Amadan

Reputation: 198314

You queried it too fast. You have to give the image some time to load. Best would be to bind the load handler and read width there.

Upvotes: 2

Austin Brunkhorst
Austin Brunkhorst

Reputation: 21130

You have to wait until the image loads. Try this

iconOS_img.onload = function() {
    alert(this.width);
}

Upvotes: 6

Related Questions