Reputation: 9736
There are plenty of examples showing how to dynamically set an iframe
's height to its content. This works perfect for me. The problem I'm now having is that the content can change size without triggering onload
(think hidden/expandable div
s).
Is there any way to detect when the size of the iframe
content has changed? This is on the same domain and no jQuery, please.
Upvotes: 14
Views: 15628
Reputation: 1
<iframe src="{{ encuesta_lime_sourvey_BASE_URL }}"
frameborder="0"
style="width: 100%; height: 3100px;"
id="encuesta"
>
</iframe>
function setHeight(height) {
document.getElementById('encuesta').style.height = height + 'px';
}
let iframe = document.getElementById('encuesta');
iframe.onload = function() {
const iframeEle = document.getElementById('encuesta');
const observer = new ResizeObserver(() => {
setHeight(iframeEle.contentDocument.body.scrollHeight);
});
observer.observe(iframeEle.contentDocument.body);
});
For my works this, you have to check if the iframe is loaded and is loaded you can manipulate
Upvotes: 0
Reputation: 83
ResizeObserver worked for me:
const iframe = document.getElementById('myIframe')
const observer = new ResizeObserver(() => {
setHeight(iframe.document.body.scrollHeight);
})
observer.observe(iframe.document.body);
Upvotes: 2
Reputation: 26
For non-webkit browsers, there are a few domMutation-Events, that fire when an attribute of an element (e.g. the body element) change. See DOMSubtreeModified and more importantly DOMAttrModified.
The internet explorer does fire the onresize event even on non-windows elements.
Opera honors the domMutation Events.
Webkit on the other discarded these events as a compromise to rendering speed and javascript-performance. Thee is no other way than to check via timeout/interval the effective size of an element.
Upvotes: 0
Reputation: 237847
I would do this by polling regularly (maybe every 200 milliseconds, perhaps more often) using setInterval
. You could then compare the size of the content to what it was last time.
var iframe = document.getElementById('myIframe'),
lastheight;
setInterval(function(){
if (iframe.document.body.scrollheight != lastheight) {
// adjust the iframe's size
lastheight = iframe.document.body.scrollheight;
}
}, 200);
Upvotes: 15