coder and technology lover
Adapting iframe height to its content with 2 lines of javascript
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"; } |
| Print article | This entry was posted by Davide Zanotti on 12, Friday f, 2009 at 2:38 am, and is filed under javascript. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 9 months ago
I am at a loss as to why this is not working. Please advise!
I have inserted all the data as you have stated, yet still am having no luck in regards to having the iframe extend to 100% of the height of the page being iframed into the site.
Here is my code:
And at the top of the page before the tag I input this:
function resizeIframe(iframeID) {
var iframe = window.parent.document.getElementById(iframeID);
var container = document.getElementById(“content”);
iframe.style.height = container.offsetHeight + “px”;
}
//–>
Thanks for the help-
Charles
about 9 months ago
Opps….it cut out my code. Here is the code:
about 9 months ago
You can’t write code directly in the messages, give me a link to your test instead ;-)