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:
- trigger the read/write of the
height
right after I know the element is visible again. - use
setTimeout()
to wait half-second (feels sluggish ) before reading/writing theheight
of the element.
Note (the actual question)
I am trying to find less hacky as possible solutions; so I want to avoid:
- displaying (or cloning) the element quickly (taking care saving+restoring css properties, making them persistent and inline; or taking care of avoiding flickering in the page), to read the dimensions and quickly set it back to hidden ().
- using
setTimeout
to wait the element dimensions being restored (and readable/writeable correctly) in order to work on them immediately after showing the element itself.