Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get height of image inside a hidden div

Tags:

jquery

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).


$('body').append('<div id="init"><img id="myimg" src="someimage.png" /></div>');
$('#init').hide();
$('#myimg').height(); // == 0
$('#myimg').width(); // == 0

How can i get the correct height/width of the image? I need it to make some decisions :-)

Best regards, Biggie

like image 274
Biggie Avatar asked Sep 21 '10 14:09

Biggie


People also ask

How can I get specific height of a div?

Method 1: Using the offsetHeight property: The offsetHeight property of an element is a read-only property and used to return the height of an element in pixels. It includes any borders or padding of the element. This property can be used to find the height of the <div> element.

Does display none have height?

Does display none have height? As mentioned in the first difference, an element with display: none doesn't take any space on the page. Hence, all properties related to the element size, such as clientHeight , clientWidth , height , offsetHeight , offsetWidth , scrollHeight , scrollWidth and width are zero.

How do you find the content height?

Using jQueryjQuery has the . height() method, which returns an element's content height. For example, the following code returns 100, which is equal to the original height of div.


3 Answers

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

like image 71
Samuel Mburu Avatar answered Nov 05 '22 21:11

Samuel Mburu


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/

like image 26
RobertPitt Avatar answered Nov 05 '22 22:11

RobertPitt


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();
like image 5
Yi Jiang Avatar answered Nov 05 '22 21:11

Yi Jiang