Tag Archives: iframe

Dynamically resizing an iframe

For a website I’m currently working on, I have an iframe in place for implementing a forum into the site, so the forum always fits nicely into the layout, also whenever the layout changes. There was only one problem with this setup, the height of the iframe was statically set and whenever a visitor was viewing a larger page/topic a scrollbar would appear within the iframe, which looks pretty nasty.

The ideal situation would be for the iframe to dynamically change it’s size whenever another page was loaded. It took a bit of trial and error, but eventually I found a way to get it done. I created this JavaScript function (inspired by various similar examples out there) to get the job done for me.

function frameResize(frameObj) {
    var frameHeight;
 
    // Reset the height back to it's original (shrink the frame)
    frameObj.height = '200px';
 
    // Set the frame height to match the content
    frameHeight = frameObj.contentWindow.document.body.scrollHeight;
    frameObj.height = frameHeight + 'px';
}

In order for this to work, don’t forget to add the onLoad attribute to your iframe which calls the function, like this:

<iframe src="some_page.html" width="100%" height="200px" id="iframe" marginheight="0" frameborder="0"
onLoad="frameResize(this);"></iframe>