Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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/

like image 774
user2665846 Avatar asked Aug 08 '13 20:08

user2665846


2 Answers

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;
like image 169
Adam Tal Avatar answered Nov 12 '22 13:11

Adam Tal


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.

like image 2
dandavis Avatar answered Nov 12 '22 12:11

dandavis