Monday, June 13, 2011

Javascript: Automatically adjust iframe height to fit content

This solves the need to adjust the height of an iframe depending on the length of the content inside the iframe. The iframe may contain images, text, etc.

This solution is also appropiate for the situations when you have a form inside an iframe and the number of the fields of the form changes dynamically (javascript) depending on user actions. Also the display of form errors above the form may be a cause for content stretching over the predefined height of the iframe.

Technical description: The height of the iframe's content is read from inside the iframe and a function from the parent window is called in order to modify the height.

File 1, dynamic-height-adjusting-iframe.html :

<html>
<head>
<title>read element height</title>
<script type="text/javascript">
function adjustIframeHeight(_h) {
    var new_h = _h + 50;
    document.getElementById('my_iframe').style.height = new_h + 'px';
}
</script>
</head>

<body>

<div>
Other text here<br/>
Other text here<br/>
Other text here.<br/>
</div>

<iframe id="my_iframe" src="dynamic-height-adjusting-iframe-content.html" width="730" height="650" scrolling="no" frameborder="1" marginwidth="0" marginheight="0" style="border-top:2px solid #ccc;border-left:2px solid #ccc;border-right:2px solid #ddd;border-bottom:2px solid #ddd;"></iframe>


</body>
</html>


File 2, dynamic-height-adjusting-iframe-content.html :

 <html>
<head>
<title>read element height</title>
<script type="text/javascript">
function getXYpos(elem) {
   if (!elem) {
      return {"x":0,"y":0};
   }
   var xy={"x":elem.offsetLeft,"y":elem.offsetTop}
   var par=getXYpos(elem.offsetParent);
   for (var key in par) {
      xy[key]+=par[key];
   }
   return xy;
}
function getHeightBetweenElements(elem1, elem2) {
    var xy1 = getXYpos(elem1);
    var xy2 = getXYpos(elem2);
    return xy2.y - xy1.y;
}
function adjustMySelf() {
    var h = getHeightBetweenElements(document.getElementById('pos-reper1'), document.getElementById('pos-reper2'));
    parent.adjustIframeHeight(h);
}
</script>
</head>

<body>
<div id="pos-reper1"></div>

<div style="width: 300px; margin: 0 auto;">
text sakfjdsio fdiojsifojdsio fjdiojs fds
text sakfjdsio fdiojsifojdsio fjdiojs fds
text sakfjdsio fdiojsifojdsio fjdiojs fds
text sakfjdsio fdiojsifojdsio fjdiojs fds
text sakfjdsio fdiojsifojdsio fjdiojs fds
text sakfjdsio fdiojsifojdsio fjdiojs fds
text sakfjdsio fdiojsifojdsio fjdiojs fds
text sakfjdsio fdiojsifojdsio fjdiojs fds
text sakfjdsio fdiojsifojdsio fjdiojs fds
text sakfjdsio fdiojsifojdsio fjdiojs fds
</div>

<div id="pos-reper2"></div>

<script type="text/javascript">
adjustMySelf();
</script>
</body>
</html>

2 comments:

saidesh said...

This is not working in IE6 and IE 8
did't checked in IE 7

engine9pw said...

One important mention: the frame url should be on the same domain with the parent window.