I've found a way to getBoundingClientRect
from a hidden element: Make its display
style to initial
so the browser can calculate properly. Then hide instantly the element so it never shows up to the user.
But it doesn't work on IE. It always returns 0
.
How can I make this work on IE?
var element = document.querySelector('#foo');
console.log('Element is hidden', element.getBoundingClientRect());
element.style.display = 'initial';
console.log('Element shows for little time', element.getBoundingClientRect());
element.style.display = 'none';
<div id="foo" style="display: none;">Guess my size, I'm hidden !</div>
Sadly, IE doesn't support initial
value (mdn). So the assignment does nothing, and the element remains hidden, that's why you get 0 as a resulting height.
But even if it did, it wouldn't have worked the way you expected: display: initial
sets the universal initial value for display
for all the affected elements - that's inline
both for div
s and span
s. Here's little proof-of-concept of this behaviour.
Instead you have to cache the original value of display
by your own code before hiding it. Actually, that's exactly what jQuery and other popular frameworks do with their implementation of .hide()
:
The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css( "display", "none" ), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline and is hidden then shown, it will once again be displayed inline.
This might answer the question indirectly - another option if you need to getBoundingClientRect() for a hidden element is to hide it in a different way (other than display:none). Setting color and/or background-color to transparent, for example.
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