Iframe dynamic resizing… SOLVED!

UPDATE (05/06/2008): Check out my next post for a better solution using CSS.

During the E2 development I ran into a very annoying iframe resizing problem. In simple terms iframe did not automatically resize in IE after the contents of the iframe had been loaded. This used to drive me nuts since the iframe appeared to be working fine in Firefox and Safari. I looked and tried a lot of solutions available on the web and finally came up with a Prototype, javascript solution which seems to be working like a charm! So heres the code…

  • The page with an iframe

<html>
<head>
<tittle>Iframe Resizing</title>
<script type=”text/javascript” src=”resize.js”></script>
</head>
<body>
<iframe width=”100%” height=”100%” scrolling=”auto” id=”iframe” name=”iframe” frameborder=”0″ src=”SOMETHING.HTML” /></iframe>
<script type=”text/javascript” language=”JavaScript”>
new Resize();
</script>
</body>
</html>

  • The Prototype based javascript (resize.js )

function Resize() {
this.init();
}
Resize.prototype = {
init: function() {
var userAgent = new String(navigator.userAgent).toLowerCase();

if (userAgent.indexOf(“msie”, 0) > 0) {//Only call it on IE
Event.observe(window, ‘load’, this.resizeIFrame.bindAsEventListener(this)); //This is where the magic happens
}
},

resizeIFrame: function() {  
var frame = $(‘iframe’);  
var renderedDocumentHeight = frame.contentWindow.document.body.scrollHeight;  

if (renderedDocumentHeight < 600) {       
renderedDocumentHeight = 600;//Set a minimum height in case the document is really small
}  
frame.height = renderedDocumentHeight;
}
}


About this entry