How bad is to do a hide of a hidden element?
So, let's say the element #myelement
is hidden, and I do a $('#element').hide()
. Is that bad? Should I check if it's visible first?
Thanks!
Completely hiding elements can be done in 3 ways: via the CSS property display , e.g. display: none; via the CSS property visibility , e.g. visibility: hidden; via the HTML5 attribute hidden , e.g. <span hidden>
The following style rule hides an element on a web page: display: none; When you set the value of display to none, the affected element will disappear. This means the element will no longer take up any space on the web page.
visibility:hidden hides the element, but it still takes up space in the layout. display:none removes the element from the document. It does not take up any space.
CSS Display Property. Each element has a default display value like inline-block , block , table ..etc. To hide an element with the display property, we should use display: none . When an element is hidden with display: none , all of its descendants will be removed along with it.
jQuery checks if the element is visible and hides only if it's visible: https://github.com/jquery/jquery/blob/master/src/css.js#L78
} else if ( !values[ index ] && !isHidden( elem ) ) {
jQuery._data( elem, "olddisplay", curCSS( elem, "display" ) );
}
So you don't need to perform additional checks. Any manual check would make the performance (and readability actually) worse.
If there is a choice between
$("my-element").hide();
and
if(!$("my-element").is(":visible")) {
$("my-element").hide();
})
it is much simpler (better?) to just have the first line for readability sake. jQuery will do the check whether you do it or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With