0

I have the following code which needs to get the width of an image which is dynamically loaded, when a thumbnail is clicked on.

$("<img class='mypopupimage' src='" + imgSrc + "' style='padding:10px;' width='500' />").appendTo("div.mydiv");

var imgWidth = $(".mypopupimage").width();

The trouble I have is that the popup images are all different widths, but when I remove the width attribute from the image the imgWidth variable gets set to 0.

Any ideas?

Tom
  • 12,776
  • 48
  • 145
  • 240
  • 2
    Dublicate of [this](http://stackoverflow.com/questions/439358/javascript-function-to-get-real-image-width-height-cross-browser): Try $(".mypopupimage").attr("naturalWidth"); – Sgoettschkes Aug 31 '11 at 09:17
  • Awesome, thanks... if you add this as an answer I can accept it as the correct one... – Tom Aug 31 '11 at 09:25
  • 1
    possible duplicate of [How to get image size (height & width) using javascript?](http://stackoverflow.com/questions/623172/how-to-get-image-size-height-width-using-javascript) – Shadow The GPT Wizard Aug 31 '11 at 09:27
  • Tom just upvote the accepted answer in the duplicate if it helped you as well. – Shadow The GPT Wizard Aug 31 '11 at 09:28

2 Answers2

1

This has already been answered multiple times on stack, however, here it is for ease:

clientWidth and clientHeight are DOM properties that show the current in-browser size of the inner dimensions of a DOM element (excluding margin and border). So in the case of an IMG element, this will get the actual dimensions of the visible image.

var img = document.getElementById('imageid'); 
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;

This answer is taken from here

Community
  • 1
  • 1
udjamaflip
  • 682
  • 1
  • 8
  • 24
0

You should use the attribute naturalWidth if you want to use jQuery or go with the "normal" javascript as stated by udjamaflip:

$("<img class='mypopupimage' src='" + imgSrc + "' style='padding:10px;' width='500' />").appendTo("div.mydiv");
var imgWidth = $(".mypopupimage").attr('naturalWidth');
Sgoettschkes
  • 13,141
  • 5
  • 60
  • 78