3

I'm loading the source of an image dynamically using ajax, where s is this source. I create an image element in the DOM, assign it this source once it's loaded, and then append it to a div called imgwrapper. Then I try to get the image's dimensions, but it doesn't work. I'm aware you can't get the dimensions of an image that's dynamically loaded, but not even after being appended to the DOM?

My code is as below:

//use ajax to get value of s (the image source)
img = document.createElement("img"); 
img.src = s; 
$('#imgwrapper').appendChild(img); 
console.log($('#imgwrapper').find('img').width());

this returns 0, instead of giving me the image's width.

1
  • 3
    Are you sure it's in the DOM? There's no $.appendChild(), that should be $.append(). On another note, you don't need to reselect the element after it's appended, you can just wrap img in a jQuery object: $(img).width(). Commented Jan 15, 2013 at 10:22

2 Answers 2

4

Wait till the image has finished loading

//use ajax to get value of s (the image source)
img = document.createElement("img"); 
img.onload = function() {
    console.log($('#imgwrapper').find('img').width());
};
img.src = s; 

$('#imgwrapper').append(img);

Edit
As @MattiasBuelens mentioned. There is no .appendChild() for a jQuery object. That should be .append() instead

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

2 Comments

Another optimization: use $(img) in the handler instead of reselecting.
If you really want to, you could go completely jQuery on this and use $(img).on('load', function() { ... }); to bind the load handler.
0

You can try this:

img = document.createElement("img"); 
img.src = "http://placehold.it/350x150"; 
$('#imgwrapper').append(img); 
console.log($('#imgwrapper').find('img').width());

Working example: http://jsbin.com/adajuh/1/

3 Comments

you need to use append instate of appendChild
anyway it is answered above from @Andreas
This doesn't work, it still gives 0 on the first load. When you load it the second time, it works since the image is already in the cache - but that's cheating. Try it yourself: press Ctrl+F5 and check the console.

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.