3

I have, what I think is, a strange issue. I am running a simple query that finds the largest image on a page. Here is some test data - all images are 32x32 but one is sized to 300x300.

<img src="app/assets/images/icons/blue.png" />
<img src="app/assets/images/icons/error.png"/>
<img src="app/assets/images/icons/info.png" height="300" width="300"/>

If I run a simple query like this:

$('img').each(function(){
        console.log($(this).height());
    });

I will get 0,0,300 — and not 32,32,300.

Can anyone point me to a better method of finding the size the image is being rendered at?

Thanks.

Ad Taylor
  • 2,775
  • 5
  • 27
  • 32
  • I think this may help: http://stackoverflow.com/questions/318630/get-real-image-width-and-height-with-javascript-in-safari-chrome – Tom Haigh Feb 27 '10 at 23:20

2 Answers2

3

If the image is "natively" sized, i.e. no width or height are present in the HTML, you'll need to wait for the image to load before you know its size. I use this:

jQuery("img").each(function(){
    var img = jQuery(this);
    if (img.attr("complete")) {
        console.log(img.height());
    } else {
        img.load(function(){
            console.log(img.height());
        });
    }
});
jpsimons
  • 27,382
  • 3
  • 35
  • 45
-1

Make sure you do it after the image is ready in $(img).load(), then it will work. Try JavaScript to verify:

function iLoad(isrc) {
var oImg = new Image();
oImg.src = isrc;
if (oImg.complete) {
window.alert(oImg.src + ' ' + oImg.width + ' x ' + oImg.height);
alemjerus
  • 8,023
  • 3
  • 32
  • 40