Kamafeather
Kamafeather

Reputation: 9845

Get reliably the height of an hidden element

The problem context

I need to resolve the height of the content of an iframe after loading it (in order to adapt the height of the iframe element itself). The problem is that the iframe could be in a hidden state (one of its containers/parents set to display:none), when the loading is done.

I can't find a way to get the correct height of the iframe content as long as I don't display it. Using jQuery.height() returns 0 on Firefox.


An example demo here:

https://codepen.io/anon/pen/gKBQeP?editors=1111

(you'll notice how the height is reported differently in case you immediately click on the Tab3, where the iframe is, making that visible, or if you wait a couple of seconds after loading and then click on the Tab3)


Cannot write height on the element, right after displaying it.

Moreover, after making it visible again I still cannot get the real height of the content; it still returns 0 like it is hidden. I assume because the iframe-content is still in the process of getting rendered, even if the DOM tree of the iframe has been shown already. If I setTimeout few milliseconds after making it visible then I can get the correct height (that doesn't make much sense to me....🤔).

I really don't like to set a timeout in order to read the content height.

What is a reliable, cross-browser, way to get the height of a hidden element, even when this is hidden (or in the process of becoming visible)?

My solution

At the moment I:

Note (the actual question)

I am trying to find less hacky as possible solutions; so I want to avoid:

Upvotes: 1

Views: 112

Answers (1)

emmzee
emmzee

Reputation: 640

It's a bit hacky but rather than display:none (I assume that's how it's being hidden) you could set something like:

top: -10000px;
left: -10000px;
position: absolute;

It's "hidden" since it won't be visible, but you will still be able to get its height. Then after you get the height you can remove these styles to make it visible.

Upvotes: 1

Related Questions