March 24, 2008

Dynamically resizing iFrame height

Many of us who have used iframes, or tried, know that you cannot give an iframe a height of 100% and have it actually use 100% of the available space. Internet Explore, Firefox and Safari to not actually give the iframe a height of 100%. The only way you can set an iframe’s height is using a fixed measurement like pixels. This can be quite an inconvenience as we do not know what the size of our user’s browser is.

What we have to do to get a dynamic iframe that we can set to use an amount of space unknown is to use JavaScript. We can use JavaScript to get the height of the browser’s viewable area in pixels and then subtracted the height of any banner or other contents at the top of the page. Finally all we need to do is set the function to fire on resize. Ta da! A dynamically resizing iframe!

// Declare the function
function iFrameHeight() {

// Get the iframe with the id or "iFrame1"
var q=document.getElementById('iFrame1');

// Get the div with the id "containerTop".
// This could contain a banner or other content.
var r=document.getElementById('containerTop');
var qHeight = window.innerHeight;
var browser = navigator.userAgent;

// Browser detection to determine how we
// get the height of the viewable area.
isB = browser.indexOf("MSIE");
if ( isB > -1 ) {

// IE, FF
a = document.documentElement.clientHeight;
}
else {

// Safari & FF & Opera
a = window.innerHeight;
}

// Browser detection to ensure the page does not get large enough to require a vertical scroll bar.
isB = browser.indexOf(”Firefox”);
if ( isB > -1 ) { a = a - 5; }
isB = browser.indexOf(”Opera”);
if ( isB > -1 ) { a = a - 5; }

// Set the proper height of the iframe.
newH = a-r.offsetHeight ;
q.style.height = newH + “px”;
}

// Set our function to fire when the browser is resized.
window.onresize = iFrameHeight;

Dynamically resizing iFrame height demo. Do not forget to use a Reset style sheet to override browser defaults!

~Nathan Hein

Leave a Reply