i want to to get the height/width of an image inside a hidden div-containter, but .height()
and .width()
both returns 0 (like expected).
I had a similar problem. The thing is that if an image or div containing an image has style="display:none" then its css height=0. I found that the height() and width() functions gave the wrong values, eg 0! The solution for me was to ensure that the images have their attributes set so even if they are hidden the values are still accessible. So use:
$('#testImg').attr('height') and $('#testImg').attr('width') to get the height and width of the image.
it looks like you need to compute the height & width of an image. if so, you're thinking of it too hard.
I just ran across the solution for this, what you do is instead of rely on jQuery to do this for you. Instead, get the javascript element and get the height off of the element itself, as follows:
var img = hiddenDiv.children('img');
var imgHeight = img.get(0).height;
var imgWidth = img.get(0).width;
The jQuery method get(0)
allows us to get at the underlying DOM element and interestingly enough, the DOM element dimensions don't change.
One note though, for performance reasons, you will want to cache the img.get(0)
if you plan on using it more.
jQuery get method documentation
you have to use find()
$('body').find('#myimg').width();
or
$('body').find('#myimg').attr("width");
becouse you have appended it after the DOM was loaded
Its because the image has not loaded yet.....
$('body').append('<div id="init"><img id="myimg" src="something.png" /></div>');
$('#init').hide();
$('#myimg').bind("load",function(){
alert(this.height) //works
})
heres a test: http://jsfiddle.net/WMpSy/
You can't hide it if you want the correct height and width, but you can move it such that it will be out of the screen, and thus effectively hidden. Try this:
var hiddenDiv = $('<div id="init"><img id="myimg" src="someimage.png" /></div>').appendTo('body').css({
'position': 'absolute',
'top': -9999
});
var img = hiddenDiv.children('img');
img.height();
img.width();