JQuery outerHeight() return none-zero on hidden (display:none) element?

3.6k views Asked by At

I think it should return 0 for display:none elements. but it doesn't, at least for 1.10.1

<div id="a" style="display:none">
    asdf
    asdfasdf<br>
    sadf
</div>

alert($('#a').outerHeight(true))

http://jsfiddle.net/pUuAz/

2

There are 2 answers

1
Adam Tal On BEST ANSWER

jQuery gives you the height of the element regardless to if it's displayed on the screen.

If you want it to ignore an hidden element use the following:

$('#a').is(':visible') ? $('#a').outerHeight(true) : 0;
0
dandavis On

digging into $.css to $.style to $.cssHooks to $.cssHooks.height.get we see the culprit:

function ( elem, computed, extra ) {
            if ( computed ) {
                // certain elements can have dimension info if we invisibly show them
                // however, it must have a current display style that would benefit from this
                return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
                    jQuery.swap( elem, cssShow, function() {
                        return getWidthOrHeight( elem, name, extra );
                    }) :
                    getWidthOrHeight( elem, name, extra );
            }
}

it seems they swap the style, rip the value, then swap it back to display:none.