I’m trying to get an iframe into loading at its full height.
I am working from within the confines of WordPress Elementor, but I don’t think that’s holding me back.
I have a section on a page
<iframe id='iframe1' src="https://example.com/my.html" style="display:none" title="iframe1"></iframe>
So the iframe is in the DOM with display initially set to none.
When the user clicks a button on the page, a function does two things
-
it sets
theIFrameTag.style.display="inline-block";
-
theIFrameTag.addEventListener('load', syncHeight);
where the function syncHeight is
function syncHeight() {
this.style.height = `${this.contentWindow.document.body.scrollHeight}px`
}
It seems that this.contentWindow.document.body.scrollHeight is initially set to 150 when display is none and so when my function runs, it’s that height not the actual height.
Is there a way to get it to display real height (to display the whole thing and avoid the need for a scroll bar)? Obviously, something has to know the actual height since its displaying that in the 150 pixel high window with a scroll bar.
2
Answers
So it seems that when an iframe is already part of the DOM displayed or not, it's "loaded" and it doesn't load again by changing the display attribute. So the function assigned to listen on load events never gets called. The solution at least as far as drawing the iframe at the right size is to use the MutationObserver to observe for changes to the display attribute. First in the button function do the following
The observeIFrameChange function is as follows
Just change
To
for more info your can look here https://www.w3schools.com/cssref/css_units.asp