Reputation: 63309
I want to set the width and height of the container <div>
of <img>
after the image is downloaded, how to do it?
Upvotes: 0
Views: 69
Reputation: 2587
It is best to wait for the image to be loaded unless you want false results.
jQuery('#image').load(function() {
var jThis = jQuery(this);
var width = jThis.width();
var height = jThis.height();
yourFunction(width, height); //whatever you want to do with these values
jThis.unbind('load'); //might be necessary if you only want this to happen once. Remove this if #image is a container for multiple uses.
})
Instead of yourFunction()
, you could use this since it fits your description better:
jThis.parents('#container').css({
width: width,
height: height
});
Upvotes: 0
Reputation: 2555
function fn (div, url_path) {
var img = new Image();
img.onload = function () {
div.style.width = img.width;
div.style.height = img.height;
};
img.src = "url_path";
}
fn(document.getElementsByTagName('div')[0], 'http://some-url-to-image.com/1.jpg');
Upvotes: 1