9

Possible Duplicate:
Resizing an iframe based on content

I'm trying to load one of my pages into an iframe. I'm never sure how big the page will be, the data on the page is loaded dynamically. I'd like the iframe to always fit the page, no matter how big or small it is. Here's what I have:

function loadModal() {
    myframe = $('<iframe id="mymodal" src="MyPage.aspx" width="700"></iframe>');

    myframe.appendTo($('html'));

    var height = document.getElementById('modalPreview').contentWindow
                     .document.body.scrollHeight;

    $("#mymodal").attr("height", height);
}

I've been trying to get the height of the page after it's loaded. The problem is that height comes back as 0. But if I do this:

    setTimeout(function () {
        $("#mymodal").attr("height", height);
    }, 2000);

the correct height is loaded. I assume it's because the data needs a few seconds to load. But this looks funky if the page loads really fast, or it will still give me a height of 0 if it takes more than 2 seconds to load the page.

So is there a way to:

  1. Wait and set the height of the iframe once the data loads, or
  2. Set the height of the parent iframe from MyPage.aspx?
Community
  • 1
  • 1
Steven
  • 16,943
  • 64
  • 174
  • 272

2 Answers2

12

If you're going to use option #2 you can access the parent window using the DOM and set the iframe height from the child.

$(document).ready(function() {
    var iframeWin = parent.document.getElementById("yourIframeID");
    iframeWin.height = document.body.scrollHeight;
});
Matt K
  • 6,287
  • 3
  • 35
  • 53
  • 4
    Will not work if iframe url is not on the same domain. – gfivehost Mar 18 '14 at 15:24
  • 1
    @ricky Correct, that is because of the cross-origin issue. Just enable CORS in your .htaccess or apache config or any other number of ways and you can accomplish the same thing. – Matt K Mar 18 '14 at 16:05
1

You can hook an onload event to the Iframe before you insert it. When it fires, inspect the height of the document in the iframe and adjust its height accordingly.

Diodeus - James MacFarlane
  • 107,156
  • 31
  • 147
  • 171
  • will the `onload` event trigger if there is an ajax call in there? Say we load the frame and the JS adjusts the height, but then the height is dynamically changed again due to an ajax call, will the `onload` event trigger again? – Philll_t Aug 24 '15 at 16:45
  • Where does the ajax call happen? In the iframe or the parent? – Diodeus - James MacFarlane Aug 24 '15 at 18:51
  • No. the `onload` event is only fired when the page first loaded, or a form post afterwards. Ajax call won't trigger onload event of iframe – Bo Chen Dec 16 '16 at 01:33