user961627
user961627

Reputation: 12747

find the dimensions of a dynamically loaded but DOM-appended image using jquery?

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.

Upvotes: 3

Views: 618

Answers (2)

Razmig
Razmig

Reputation: 629

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/

Upvotes: 0

Andreas
Andreas

Reputation: 21881

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

Upvotes: 4

Related Questions