4

I need to get an image's dimensions in javascript (jQuery) when no styles are specified for it (jQuery's css() returns 0).

Maybe it is because I'm loading the image with jQuery just before asking for its dimensions. If this is the case, is there any event to listen that tells when the image has been loaded?

Gerardo
  • 1,928
  • 4
  • 24
  • 34

5 Answers5

3

Maybe the image has not fully loaded therefore the dimensions can not be given.But without your code I can't tell what you're doing wrong, but here is an Example that would work:

function LoadImage(isrc) {
    var oImg = new Image();
    oImg.src = isrc;
    if (oImg.complete) {
        window.alert(oImg.src + ' ' + oImg.width + ' x ' + oImg.height);
    }
    else {
        window.setTimeout('iLoad(imgsrc)', 1000);
    }
}

<body onLoad='LoadImage(imgsrc)'>
ankitkanojia
  • 3,072
  • 4
  • 22
  • 35
TStamper
  • 30,098
  • 10
  • 66
  • 73
  • complete does not seem to work for chrome. That worked for me so far: http://stackoverflow.com/questions/318630/get-real-image-width-and-height-with-javascript-in-safari-chrome – 2ni Jan 09 '10 at 17:10
1

here's a link that helps, look at the demo: http://docs.jquery.com/Events/load

with jquery there is a load() event that's fired when an image is done loading ie:

<script type="text/javascript">
    $(document).ready(function()
    {
        $('#theImage').load(function()
        {
            // do the stuff here.
        });
    });
</script>


<img src="blah.jpg" id="theImage" />
John Boker
  • 82,559
  • 17
  • 97
  • 130
0

Depending on what you're after image.width or image.naturalWidth (and height equivalents) width/height gives the width/height attributes on the image tag, naturalWidth/Height gives the dimensions of the actual underlying image.

olliej
  • 35,755
  • 9
  • 58
  • 55
0

You can use img's onload to get the dimensions once the image has loaded:

<img src="..." onload="getDimensions(this)" />
Dan Lew
  • 85,990
  • 32
  • 182
  • 176
0

You can try to combine karim79's and John Boker's answer. Try to preload the image into hidden DOM and when it loads you can try to get its width&height.

Ferry
  • 250
  • 3
  • 8