Automatically Resize an IFrame From It’s Content

May 23, 2009

I recently had a situation with a client where I needed to use an iframe to pull content from a bulletin board into their main site template. Setting up the iframe was the easy part, then I noticed that the content would auto size the width, but it would not autosize the height. As I wanted this iframe to look like it was part of the page, not an iframe, I started googling. There are lots of “solutions” out there to make the iframe automatically resize the height, but I did not find one that actually worked how I wanted it. The closest I came to finding what I was looking for was creating a div around the iframe, and with javascript get the content of the iframe and replace the content of the div. This actually works out really well, until you clicked a link inside the iframe and it broke out of the iframe. So I did some looking at javascript methods and I came up with a pretty good solution myself. You can use this to automatically resize your height, and still use the links inside the iframe. It looks like the iframe is part of your actual page, and nobody is the wiser.

function resizeIFrame() {
     var myIFrame = document.getElementById('YourIframeName');
     myIFrame.height = myIFrame.contentWindow.document.body.scrollHeight + 10;

Be sure to change the name of the iframe you are trying to get. Here is an example of the HTML I used.