Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
121
rated 0 times [  127] [ 6]  / answers: 1 / hits: 16247  / 15 Years ago, tue, july 7, 2009, 12:00:00

I'm writing a jQuery function where I'd like to access both the native size of an image, and the size specified for it on the page. I'd like to set a variable for each.



How is that done?


More From » jquery

 Answers
25

Modern browsers



When I wrote this answer back in 2009 the browser landscape was much different. Nowadays any reasonably modern browser supports Pim Jager's suggestion using img.naturalWidth and img.naturalHeight. Have a look at his answer.



Legacy answer compatible with super old browsers



// find the element
var img = $('#imageid');

/*
* create an offscreen image that isn't scaled
* but contains the same image.
* Because it's cached it should be instantly here.
*/

var theImage = new Image();
theImage.src = img.attr(src);

// you should check here if the image has finished loading
// this can be done with theImage.complete

alert(Width: + theImage.width);
alert(Height: + theImage.height);

[#99176] Thursday, July 2, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shannon

Total Points: 606
Total Questions: 106
Total Answers: 111

Location: Lesotho
Member since Thu, Jun 30, 2022
2 Years ago
;