Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to getBoundingClientRect from a hidden element? (doesn't work on IE)

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>
like image 901
Elfayer Avatar asked Oct 18 '22 16:10

Elfayer


2 Answers

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 divs and spans. 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.

like image 198
raina77ow Avatar answered Nov 01 '22 11:11

raina77ow


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.

like image 32
Dan Kennedy Avatar answered Nov 01 '22 11:11

Dan Kennedy