Pither.com / Simon
Development, systems administration, parenting and business

Resize iframe from within

I recently needed to dynamically resize an iframe based on the size of it's content. This needed to be done for each page loaded within the iframe (as they are of varying length) to avoid an extra level of scrollbars appearing.

You can skip ahead to see the finished product here: Sutton Footprint Calculator. The details of the solution I ended up with are below.

The parent page (the one defining the iframe tag, but not the content) had to specifically relax access so that the contained page could resize the iframe:

<script type="text/javascript"> 
  document.domain = "oneplanetsutton.org";
</script>

Obviously this only works if you have control over both the parent and contained pages and indeed can arrange for them to both be hosted on the same domain.

The iframe defined in the parent page also had to be given a specific ID, in this case it was "calculator_iframe" (as you'll see in the code below).

Each page that was to be displayed in the iframe then needed the following (there was no Javascript framework involved, so there's also a fairly standard addEvent function defined and used):

<script type="text/javascript"> 
document.domain = "oneplanetsutton.org";
function addEvent(obj, evType, fn){ 
    if (obj.addEventListener){ 
        obj.addEventListener(evType, fn, false); 
        return true; 
    } else if (obj.attachEvent){ 
        var r = obj.attachEvent("on"+evType, fn); 
        return r; 
    } else { 
        return false; 
    } 
}
function resizeIframe() { 
    if(self == parent) return false;

    var framePageHeight = 0;
    if(document.documentElement.scrollHeight)
        framePageHeight = document.documentElement.scrollHeight + 10;
    else
        framePageHeight = document.body.scrollHeight + 10;

    parent.document.getElementById('calculator_iframe').style.height = framePageHeight + "px";
}
addEvent(window, 'load', resizeIframe);
</script>

It's not perfect with different browsers ending up with differently sized iframes but all those tested do avoid scrollbars at least.

Add a comment