4

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.

2
  • Do you have any javascript libraries (jQuery) available to use?
    – Jon
    Mar 3, 2016 at 20:09
  • Yes jquery-1.9.1.js
    – nsilva
    Mar 3, 2016 at 20:12

2 Answers 2

2

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

4
  • this doesn't seem to be resizing anything, I'm calling it on every function
    – nsilva
    Mar 3, 2016 at 20:55
  • How are you calling it? I'll update my answer with the iFrame I'm using in my example.
    – Ageonix
    Mar 3, 2016 at 20:58
  • I believe there is a missing { on line 1 of your code in this answer. Oct 17, 2017 at 13:19
  • There is indeed. I updated the answer. Thanks Menno!
    – Ageonix
    Oct 18, 2017 at 15:06
0

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

1
  • The iFrame is on the same domain.
    – nsilva
    Mar 3, 2016 at 20:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.