Resize an IFRAME based on its content

<script>
function calcIframeHeight() {
  var the_height=
    document.getElementById('iframecontent').contentWindow.
      document.body.scrollHeight;
  document.getElementById('iframecontent').height=
      the_height;
}

function go(page) {
document.getElementById('iframecontent').src=page;
}

</script>

...

<span onClick="go('topics/java-language.html')">Language</span><br>

<iframe src="welcome.html" 
    name="iframecontent" id="iframecontent" width="100%" height="100%" 
    scrolling="NO" frameborder="0" 
    onLoad="calcIframeHeight();window.scroll(0,0);">
</iframe>
The IFRAME onload event triggers a called to our javascript to resize the IFRAME.

But this is not working with IE8, the resize failed when loading a new document. It looks that there is a problem with the onload event when used in the HTML tag directly

Here an alternative technique (IE8 friendly) where we attach with javascript the required function to the IFRAME load event.


<script>

function calcIframeHeight() {
  var the_height=
    document.getElementById('iframecontent').contentWindow.
      document.body.scrollHeight;
  document.getElementById('iframecontent').height=
      the_height;
}

function onloadfunction(){
  // register handler for iframe load event
  if (document.getElementById("iframecontent").attachEvent)
     document.getElementById("iframecontent").attachEvent("onload", calcIframeHeight); // ie
  else if (document.getElementById("iframecontent").addEventListener)
     document.getElementById("iframecontent").addEventListener("load", calcIframeHeight, true); // Safari, Firefox
}

if (window.addEventListener)
   window.addEventListener("load", onloadfunction, false)
else if (window.attachEvent)
   window.attachEvent("onload", onloadfunction)
else if (document.getElementById)
   window.onload=onloadfunction
</script>   
...
<BODY>
...
<iframe src="welcome.html" 
    name="iframecontent" id="iframecontent" width="100%" height="100%" 
    scrolling="NO" frameborder="0" 
    onLoad="calcIframeHeight();window.scroll(0,0);"
>
</iframe>




If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2010
[ home ]