Subject: dynamicly resizing a iFrame

Posted on: 13/10/2013 07:19am
By: remy

Say, one has various contents loaded thru a iFrame component.
There is a button toggling this content on and off. The iFrame window does not resize now, and shows the full (maximum) length. To avoid this, the following code can be used.
PHP Formatted Code


// this is to be contained in the page loaded in a iFrame
// call toggleVisibility("myElementId") to toggle visibility of the element AND resize the iFrame
// resizing is done by this.parent.resizeMeNow()

<script type="text/javascript">
var e=null;
function toggleVisibility(id) {
   if (e) { e.style.display="none"; this.parent.restoreMeNow(); }
       e = document.getElementById(id);
   if (e.style.display == 'block') e.style.display = 'none';
   else                            e.style.display = 'block';
       
   this.parent.resizeMeNow();
}
//-->
</script>

// this has to be contained in the parent page where the iFrame will be loaded.

<script type="text/javascript" language="JavaScript">
function resizeMeNow() {
  var myNewHeight=document.getElementById('myIFrameId').contentWindow.document.body.scrollHeight;
  document.getElementById('myIFrameId').height=myNewHeight;
}
</script>

// add this attribute to the iFrame tag in this page:

onload="resizeMeNow()"
 


Of course, this (not resizing to smaller pages) also happens when several pages are loaded after each other in a iFrame. In this case you don't need the toggleVisibility-function and could use only onLoad="parent.resizeMeNow()" in the body tag.

Geeklog - Forum
https://www.geeklog.net/forum/viewtopic.php?showtopic=95280