Skip to content Skip to sidebar Skip to footer

Iframe Dynamic Height Resizing

Hi I currently have 2 pages (index.html and iframe_contents.html). Both are on the same domain. I am currently trying to get the iframe to dynamically resize based on the contents

Solution 1:

After reading lots of answers here they all had the same issue with not resizing smaller when needed. I think most people are just doing a one-off resizing after the frame loads, so maybe don't care. I need to resize again anytime the window size changes. So for me, if they made the window narrow the iframe would get very tall, then when they make the window larger it should get shorter again. This wasn't happening on some browsers because the scrollHeight, clientHeight, jquery height() and any other height I could find with DOM inspectors (FireBug/Chrome Dev Tools) did not report the body or html height as being shorter after the iframe was made wider. Like the body had min-height 100% set or something.

For me the solution was to make the iframe 0 height, then check the scrollHeight, then set to that value. To avoid the scrollbar on my page jumping around, I set the height of the parent (that contains the iframe) to the iframe height to keep the total page size fixed while doing this.

I wish I had a cleaner sample, but here is the code I have:

        $(element).parent().height($(element).height());
        $(element).height(0);
        $(element).height($(element).contents().height());
        $(element).parent().height("");

element is my iframe.

The iframe has width: 100% style set and is inside a div with default styles (block).

Code is jquery, and sets the div height to the iframe height, then sets iframe to 0 height, then sets iframe to the contents height. If I remove the line that sets the iframe to 0 height, the iframe will get larger when needed, but never smaller.


Solution 2:

This may not help you much but here is a function we have in what would be your iframe_contents.html page. It will attempt to resize the iframe in which it is loaded in a sort of self-resizing, cross-browserish, pure-JavaScript kind of way:

function makeMeFit() {
    if (top.location == document.location) return; // if we're not in an iframe then don't do anything
    if (!window.opera && !document.mimeType && document.all && document.getElementById) {
        parent.document.getElementById('youriframeid').style.height = (this.document.body.offsetHeight + 30) + "px";
    } else if (document.getElementById) {
        parent.document.getElementById('youriframeid').style.height = (this.document.body.scrollHeight + 30) + "px"
    }
}

You could put calls to it in a resize() event or following an event that changes the height of your page. The feature-testing in that method should separate out WebKit browsers and pick the correct height property.


Post a Comment for "Iframe Dynamic Height Resizing"