0

I'm trying to make dynamic iFrame height in order to fit the content of the page.

I have two pages. index.php and example.html

I insert the "example.html" as an iFrame in "index.php", content height in "example.html" is changeable.

This is my code in "index.php"

<iframe src="example.html" name="iframe1" id="myiframe" marginwidth="0"
marginheight="0" align="top" scrolling="no" width="100%" height="auto" frameborder="0">
</iframe>

<script type="text/javascript">
var f = document.getElementById("myiframe");
f.onload = function() {
  this.style.height = this.contentWindow.document.body.offsetHeight + "40px";
}
</script>

My CSS:

#myiframe {
margin: auto;
padding: 0px;
float: left;
height: auto;
min-height: 255px;
height: auto !important;        /* for IE as it does not support min-height */
height: 255px;                   /* for IE as it does not support min-height */
width: 100%;
}

The iFrame works fine but the dynamic height doesn't works at all. Any suggestions? Thanks.

Mina Hafzalla
  • 2,681
  • 9
  • 30
  • 44

2 Answers2

1

You can use jquery, it can be done by using $(window).height();

<iframe src="example.html" width="100%" class="myIframe">
<p>Hi</p>
</iframe>

<script type="text/javascript" language="javascript"> 
$('.myIframe').css('height', $(window).height()+'px');
</script>
sergio
  • 5,210
  • 7
  • 24
  • 46
1

With jQuery, place this in the parent page.

$('iframe').load(function () {
    $(this).height($(this).contents().height());
    $(this).width($(this).contents().width());
});

If they are different subdomains, you'll want to add this to both parent and iframe page:

    document.domain = "shareddomain.com"
Alex Pineda
  • 2,909
  • 2
  • 14
  • 17