views:

1098

answers:

6

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?

A: 

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
A: 

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

<img src="..." onload="getDimensions(this)" />
Daniel Lew
A: 

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
A: 

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)'>
TStamper
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
+1  A: 

You can try preloading images with jQuery (from this article)

Add the preload function:

jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

Pass the images you want preloaded:

$.preloadImages("image1.gif", "/path/to/image2.png",
"some/image3.jpg");
karim79
A: 

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