Search Wiki:
Resource Page Description
Code sample on dynamic resizing of iframe to size of content

I had the need to dynamically resize an iframe to the size of its content.
The purpose was to move the scrolling from the iframe to the browser.

Finally I came up with this solution wich works fine with ie8, Firefox 3.0.6 and Safari 3.2.1.
This is a sample on adding automatic resizing of iframe element by a simple JavaScript to the size of its content.

Do not use onload attribute in iframe element to register the handler, by some reason Firefox will fire the event before the size of the iframe content have been set. If you need support for ie7 please see http://forums.asp.net/p/1181752/2005505.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Resizing Content</title>
    
    <script type="text/javascript">
	
	/*******  iframe reSizing *****
	provided asis by U. Falk, 2009
	supports ie8 on PC plus Safari 3 and Firefox 3 on both Mac and PC
	*/
 
    	function setup() {
    		// register handeler for iframe load event
    		if (document.getElementById("contFrame").attachEvent)
    			document.getElementById("contFrame").attachEvent("onload", setHeight); // ie
    		else
    			document.getElementById("contFrame").addEventListener("load", setHeight, true); // Safari, Firefox
    		// load page into iframe
    		document.getElementById("contFrame").src = "Start.aspx";
    	}
    	// adjust height of iframe
    	function setHeight() {
    		var newHeight = document.getElementById("contFrame").contentDocument.getElementsByTagName("html")[0].scrollHeight;
    		var newWidth = document.getElementById("contFrame").contentDocument.getElementsByTagName("html")[0].scrollWidth;
    		document.getElementById("contFrame").style.height = newHeight + "px";
    		document.getElementById("contFrame").style.width = newWidth + "px"; // skip line if you need static width
    	}
    </script>
</head>
<body onload="setup()">
	<iframe id="contFrame" src="" scrolling="no" frameborder="0" marginheight="0" marginwidth="0"></iframe>
</body>
</html>

Last edited Feb 28 2009 at 10:24 AM  by virrpanna, version 5
Updating...
Page view tracker