views:

84

answers:

1

Hello!

I have a div that I slide in and out. To do this I just increase the height by 2px every second until a preset height from a height of 0.

Is there anyway to determine the content height of the div as the content is unpredictible height considering the starting properties of the div are display:none and height:0?

Thank you.

+3  A: 

The trick is to temporarily show it, measure the height, then hide it again. And if you use visibility: hidden and position: absolute, it won't change the page layout while you do it.

function getElementHeight(el)
{
    var styles = {
        visibility: el.style.visibility,
        height: el.style.height,
        position: el.style.position,
        display: el.style.display
    };
    el.style.visibility = "hidden";
    el.style.height = "auto";
    el.style.position = "absolute";
    el.style.display = "block";
    var height = el.offsetHeight;
    el.style.display = styles.display;
    el.style.position = styles.position;
    el.style.height = styles.height;
    el.style.visibility = styles.visibility;
    return height;
}

If you want to get what the style height should be, you can add these two lines after var height = el.offsetHeight;:

el.style.height = height + "px";
height += (height - el.offsetHeight);
gilly3
Excellent trick! thanks.
Sanjay Manohar
A very late thank you.
Francisc