I want to set the width and height of the container <div>
of <img>
after the image is downloaded, how to do it?
Asked
Active
Viewed 65 times
0

Bin Chen
- 61,507
- 53
- 142
- 183
3 Answers
1
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');

anton_byrna
- 2,477
- 1
- 18
- 31
0
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.
})
EDIT 1
Instead of yourFunction()
, you could use this since it fits your description better:
jThis.parents('#container').css({
width: width,
height: height
});

Mike
- 2,567
- 3
- 23
- 35