Return to Snippet

Revision: 50140
at August 12, 2011 03:28 by kendsnyder


Initial Code
function autoSizeIframeHeight(iframe, header, minHeight) {
	minHeight = minHeight || 300;
	function getViewportHeight() {
		var h = document.documentElement.clientHeight;
		return document.compatMode === "CSS1Compat" && h || document.body.clientHeight || h;
	}
	function getHeaderHeight() {
		return parseFloat(getComputedStyle(header,'height'));
	}
	function getComputedStyle(el, cssprop){
		if (el.currentStyle) { // IE
			return el.currentStyle[cssprop];
		}
		else if (document.defaultView && document.defaultView.getComputedStyle) {
			return document.defaultView.getComputedStyle(el, "")[cssprop];
		}
		else {
			return el.style[cssprop];
		}
	}
	function setIframeHeight() {
		var toHeight = getViewportHeight() - getHeaderHeight();		
		iframe.height = Math.max(toHeight, minHeight);
		body.style.overflowY = toHeight < minHeight ? 'auto' : 'hidden';
	}
	var body = document.body || document.getElementsByTagName('body')[0];
	setIframeHeight();
	if (window.addEventListener) {
		window.addEventListener('resize', setIframeHeight, false);
	}
	else if (window.attachEvent) {
		window.attachEvent('onresize', setIframeHeight);
	}
}
// example usage:
// autoSizeIframeHeight(document.getElementById('MyFrame'), document.getElementsByTagName('header')[0], 300);

Initial URL


Initial Description
Given an iframe element and a header element, make the iframe just high enough to fit in the browser window. On window resize, readjust. Keep a minimum height for the iframe.

Initial Title
JavaScript Iframe Auto Resize

Initial Tags
resize

Initial Language
JavaScript