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.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Resizing Content</title>
    
    <script type="text/javascript">
    	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 27 2009 at 8:37 AM  by virrpanna, version 3
Updating...
Page view tracker