nsilva
nsilva

Reputation: 5622

iFrame - Auto Height on content change within iFrame

I have the following code:-

<script language="javascript" type="text/javascript">
  function resizeIframe(obj) {
    obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
  }
</script>

<div class="resizable">
    <iframe src="http://yellow-taxi.co.uk/onlinebooking/index.php" frameborder="0" width="100%" height="100%" scrolling="no" onload="resizeIframe(this)"></iframe>
</div>

The Javascript goes it adjusting the height to what the initial height of the iFrame is, but the height of the iFrame increases as you go through the booking process. Is there a way to auto adjust the height of the iFrame based on the content that lays inside it as the content changes?

Note: The iFrame is displayed on the same domain as the iFrame src.

Upvotes: 4

Views: 9714

Answers (2)

Ageonix
Ageonix

Reputation: 1808

Try this. No Jquery needed, but you will have to call resizeIframe when the content changes.

function resizeIframe(obj) {
    var newheight;
    var newwidth;

    if(document.getElementById){
        newheight = document.getElementById(obj).contentWindow.document .body.scrollHeight;
        newwidth = document.getElementById(obj).contentWindow.document .body.scrollWidth;
    }

    document.getElementById(obj).height = (newheight) + "px";
    document.getElementById(obj).width = (newwidth) + "px";
}

Here's an example iFrame and the necessary attributes in it. Be sure to call the above method with your iFrame name.

<iframe src="yourpage.htm" width="100%" height="300px" id="yourIframe" marginheight="0" frameborder="0" onLoad="resizeIframe('yourIframe');"></iframe>

There's also a nice JQuery plugin that will accomplish the task, and supposedly works over domains as well: https://github.com/house9/jquery-iframe-auto-height

Upvotes: 2

Jon
Jon

Reputation: 1095

Long story short, you can't, unless your page is on the same domain as the iframe page. You've run into a cross-domain limitation, and as a security measure set up by your browser, you won't be able to access JS, DOM elements, or properties within that iframe's content.

SO Explanation

Upvotes: 0

Related Questions