views:

63

answers:

5

I wonder if there is any way to get div height in pixels, although its height set earlier to 100% height.
This is required as div content is dynamic so div height has different values based on content itself.

[Edit] Div by default is hidden.

I need to get div height in pixels for later manipulation (smooth scrolling will be done for div)?
Is there any way to do this?

+5  A: 

Since you tagged jQuery, use

$("#myElement").height();

http://api.jquery.com/height/

For Plain Ol' Javascript, you can use element.clientHeight or element.offsetHeight, depending on which one suits your needs.


Since the div is hidden, you will have to .show() it before calling .height(), and you can hide it again straight away:

var $myEl  = $('#myElement').show();
var height = $myEl.height();
$myEl.hide();
Andy E
This doesn't work.Div by default is hidden.
Ahmed
element.clientHeight or element.offsetHeight return "0", as div is hidden by default.
Ahmed
@Ahmed: hidden elements have no "pixel height", so you cannot get height in pixels without showing the element first, then hiding it again afterwards. If you hide right after showing and getting the height value, the display will not be updated to show the element.
Andy E
Ahmed
+1  A: 
theDiv.clientHeight
Deniz Dogan
+1  A: 

You can use height()

$("#divInQuestion").height();
Russell Dias
+1  A: 

You could use the .height() function:

$('#divid').height()
Darin Dimitrov
A: 

Well on slow browsers the show/hide method MIGHT cause the box to flicker (though the computer have to be really slow). So if you want to avoid this, give the div a opacity: 0 - and perhaps even a position: absolute, so it doesnt push the content. So to extend the code from before:

var $myEl  = $('#myElement').css({"opacity": "0", "position": "absolute"}).show();
var height = $myEl.height();
$myEl.hide().css({"opacity": "", "position": ""});

But again. This might be overkill.

Tokimon