Dynamically resizing IFRAME as per the inner content

An IFRAME is the best way to embed a page into another page . The main problem sometimes faced is if the content within the iframe is going to change in length dynamically then at some point you will see scrollbars showing up. How to avoid this?

This can be avoided by  using javascript in the main external page in which the iframe is embedded. Every time a link is clicked within the iframe or a form submission occurs, the onload event of the iframe tag is fired. So what we do is hook that event in our external page and then calcuate what the height of the iframe should be after getting the height of the inner content .

Please note this approach only works if the iframe accesses pages within the same domain as the external page, otherwise it will throw a Security error due to cross-site scripting restrictions in javascript.

The sample html code is given below:

<div id="forum_Container">
	
	<iframe src="/Forum/index.php" id="powerhouse" frameborder="0" style="overflow:hidden;" scrolling="no" width="975px" onload = "setIframeHeight( this.id )"></iframe>
</div>

The sample javascript is given below.

function setIframeHeight( iframeId ) /** IMPORTANT: All framed documents *must* have a DOCTYPE applied **/
{
 var ifDoc, ifRef = document.getElementById( iframeId );

 try
 {   
  ifDoc = ifRef.contentWindow.document.documentElement;  
 }
 catch( e )
 { 
  try
  { 
   ifDoc = ifRef.contentDocument.documentElement;  
  }
  catch(ee)
  {   
  }  
 }
 
 if( ifDoc )
 {
  ifRef.height = 1;  
  ifRef.height = ifDoc.scrollHeight;
  divh = document.getElementById("forum_Container");
  pk = Number(ifRef.height) + Number(10);
  divh.style.height = pk+"px";
  
  /* For width resize, enable below.  */
  
  // ifRef.width = 1;
  // ifRef.width = ifDoc.scrollWidth; 
 }
}

The iframe is surrounded with a DIV tag and we manipulate the height of the DIV as well as the height of the iframe.

IE ISSUES HANDLED

A lot of people are able to do iframe resizing but get the problem of scrollbars coming up in IE both horizontally and vertically. That can be taken care of by some or all the fixes given below:

1.In the pages within the iframe put the overflow and scroll atrributes in the body tag:

<body style=”overflow:hidden;” scroll=”no“>

2.Sometimes the reason why IE still shows scrollbars is more basic i.e the height and width set in CSS for the inner pages may be more than the width and height of the iframe.

We have been able to fix the scrollbar issue in IE 7,8, and 9 using the above points.

Any suggestions or queries are welcome.

Be the first to comment

Leave a Reply

Your email address will not be published.


*