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?

4
  • 2
    Dublicate of this: Try $(".mypopupimage").attr("naturalWidth"); Commented Aug 31, 2011 at 9:17
  • Awesome, thanks... if you add this as an answer I can accept it as the correct one... Commented Aug 31, 2011 at 9:25
  • 1
    possible duplicate of How to get image size (height & width) using javascript? Commented Aug 31, 2011 at 9:27
  • Tom just upvote the accepted answer in the duplicate if it helped you as well. Commented Aug 31, 2011 at 9:28

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.