Tuesday, September 20, 2011

iframes CAN have 100% height

I made a handy find the other day: a simple script that allows your iframe to expand to 100% of the page. This is currently impossible with CSS, but with a few lines of javascript, when you shout, "Expand!", your iframe will ask, "How high?!"
I found this script at: http://www.activewidgets.com/javascript.forum.10948.6/is-there-any-way-to.html

<script language="JavaScript">
 <!--
function resize_iframe()
{
	document.getElementById("info").innerHTML='iframe offsetTop: <b> '+document.getElementById("glu").offsetTop+"</b><br>body.offsetHeight:<b>"+document.body.offsetHeight+"</b>";//display some information on the screen
 
	var height=window.innerWidth;//Firefox
	if (document.body.clientHeight)
	{
		height=document.body.clientHeight;//IE
	}
 
	document.getElementById("glu").style.height=parseInt(height-document.getElementById("glu").offsetTop-8)+"px";//resize the iframe according to the size of the window
	//document.getElementById("glu").height=document.body.offsetHeight-document.getElementById("glu").offsetTop-26;
}
 
/*
	//Here is another way to define the function (this function reloads the page whenever the user resizes the page)
	window.onresize=
	function (e) 
	{
		location.reload();
	};
*/
 
window.onresize=resize_iframe; //instead of using this you can use: <body onresize="resize_iframe()">
//-->
</script>
I wanted my iframed page to appear to take up the entire page without displaying scrollbars of its own. The script on its own was displaying secondary scrollbars, but with a little CSS, I was able to get rid of them, leaving only one scrollbar:
<style type="text/css">
*, html, body {width: 100%; height: 100%; margin: 0; padding: 0;}
body {width: 100%; overflow: hidden;}
#glu {border: 0;}
</style>

Here is the iframe code you need:
<iframe src="YOUR_WEBPAGE_URL" frameborder="0" id="glu" onload="resize_iframe()" scrolling="auto" width="100%"></iframe>
And presto! You will have an iframe that takes up the entire window, which will resize to your browser window's size.

Demo: http://lukejohnson.ca/code/iframe-100-height.php