iframe Auto Height

If you ever come across a requirement to adjust height of an iframe automatically, below is the code to follow. There could me many other solutions but nothing worked for me, except below logic

<head>
<title></title>
<script>
function resizeIframe() {
obj = document.getElementById("iframe1");
tb = document.getElementById("textbox1");
if (tb.value != obj.contentWindow.document.body.scrollHeight) {
tb.value = obj.contentWindow.document.body.scrollHeight;
obj.style.height = '0px';
obj.style.height = obj.contentWindow.document.body.scrollHeight + 30 + 'px';
}
}

function timertick()
{
setInterval(function () { resizeIframe(); }, 500);
}
</script>
</head>
<body>
<input style="visibility:hidden;" type="text" id="textbox1" />
<iframe id="iframe1" onload="timertick();" src="HtmlPage2.html" scrolling="no" style="width:100%;" />

</body>

in the above code, all we're trying to do is to change the height of the iframe based on its contents height.

So, even when the contents are changing with different heights, the iframe will change automatically as there is a call the the "resizeIframe()" every 500 milli seconds.

Please download the sample files to test the logic yourself. Launch "HtmlPage1.html" then click on hyperlinks in the iframe to observe iframe height change automatically.

 

Add comment