Jacob
Jacob

Reputation: 2071

Get height of all children and apply it to parent

I am trying to calculate the height of a "height: auto" div and then apply it to the div. I've done it like this:

function center(divName) {
    $(":animated").promise().done(function () {
        var totalHeight = 0;

        $(divName).children().each(function () {
            alert(totalHeight);
            totalHeight += $(this).height();
        });

        $(divName).css("height", totalHeight + "px");
    });
}

center("#frame_01");

The HTML:

<div id="frame_01">
    <h1>Text</h1>
    <h2 id="next_frame_02">Continue</h2>
</div>

Notice the alert(totalHeight);, im using that to test the script, problem is, the scripts returns the first children with 0px but the second one correctly.

I first thought this would be because it starts to calculate before the animation is complete, therefor not getting height of first children, so I applied $(":animated").promise().done(function() { so the script waits for the animation to complete before calculating.

But this didn't solve it, any suggestions why?

Thanks in advance!

EDIT:

What Im trying to achieve is center a div, but to do that i need the height of the div. This is the CSS:

#frame_01 {
    text-align: center;
    position: absolute;
    margin: auto;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

After the height is set with background-color: red:

enter image description here

Upvotes: 2

Views: 1081

Answers (1)

Jacob
Jacob

Reputation: 2071

I solved it by changing .height() to .outerHeight(true)

Code:

function center(divName) {
    $(":animated").promise().done(function () {
        var totalHeight = 0;

        $(divName).children().each(function () {
            alert(totalHeight);
            totalHeight += $(this).outerHeight(true);
        });

        $(divName).css("height", totalHeight + "px");
    });
}

center("#frame_01");

Upvotes: 1

Related Questions