Jun 12 2009

Adapting iframe height to its content with 2 lines of javascript

Category: javascriptDavide Zanotti @ 2:38 am

In a project, I have to use an iframe and I need that its height is automatically calculated based on its content. However is not possible to accomplish this by simply setting the attribute height to 100%, instead we must smartly use javascript to dynamically assign that value after a computation. The solution I’m going to show you is not 100% my work but instead an optimization and a better implementation of clever intuitions I found on the web.
The “trick” works in this way:

1. The iframe should has an ID assigned:

1
<iframe id="slideshow_frame" src="frame.html" frameborder="0" width="100%" marginheight="0" marginwidth="0" scrolling="no"></iframe>

2. the page loaded into the iframe should contains all the html into an “easy retrievable” container (a div with an ID is perfect!):

1
2
3
4
5
<div id="content">
    <div style="background: red; width: 400px; height: 120px"></div>
    <div style="background: green; width: 400px; height: 300px"></div>
    <div style="background: yellow; width: 400px; height: 60px"></div>
</div>

3. on the iframe’s page “onload” event, a function will be executed to adjust its height:

1
2
3
4
5
6
7
8
function resizeIframe(iframeID) {
       
    var iframe = window.parent.document.getElementById(iframeID);
    var container = document.getElementById("content");

    iframe.style.height = container.offsetHeight + "px";
           
}

Tags: ,