Take the 2-minute tour ×

Suppose I have an empty placeholder <img> tag that I want to populate dynamically. I call $("img").attr("src", "somephoto.jpg") to point the element to the correct image. However, then I want to do something based on this image's width, but both $("img").width() and $("img").attr("width") return 0.

How can I get the width of the image---or better yet, is there a way to dynamically set the src of an image that is better practice and would solve my problem?

share|improve this question
Is the image free-floating or do you insert it into the DOM? –  Ates Goral Feb 1 '11 at 5:43
I actually insert it initially but then keep changing the image. However, I use images of different dimensions and need to scale them; this is why I need a way to find the widths on-the-fly. –  octopi Feb 1 '11 at 5:52
plenty of answers: stackoverflow.com/search?q=image+size+jquery –  Zathrus Writer Feb 1 '11 at 8:41
add comment

2 Answers

I would personally append the entire new image rather than using an empty img tag's src attribute.

How are they returning zero? Remember that these two methods will return a string representation of the width, ie "10px", and not the integer 10.

share|improve this answer
Even then, until the Image's onload event fires, you can't read the height and width, because the browser doesn't know them. Also, img.height and img.width are indeed Numbers. The img.style.height and img.style.width are strings. –  isaacs Feb 1 '11 at 5:46
Given that the original poster's question uses jQuery, I referring to $("img").attr("width") and $("img").width() which return strings. –  jerluc Feb 1 '11 at 5:51
add comment

You have to wait for the image to load first.

  .attr("src", "somephoto.jpg")
  .on("load", function () {
    alert(this.height()+" "+this.width())

My jQuery might be a bit rusty. Here it is in plain ol' JS

var i = new Image()
i.src = "somephoto.jpg"
i.onload = function () {
  alert(this.height + " " + this.width)
share|improve this answer
You mean .one instead of .on, right? Also, you'd need to wrap this in a jQuery object: $(this).height() –  user113716 Feb 1 '11 at 5:46
jQuery does not have an 'on' method. .bind or .load –  sunn0 Feb 1 '11 at 5:50
@sunn0: jQuery does have a .one() method which does an unbind after the handler fires the first time, which would make sense for a load handler. Not sure if that's what @isaacs is after though. –  user113716 Feb 1 '11 at 5:52
add comment

Your Answer


