Mina Hafzalla
Mina Hafzalla

Reputation: 2821

How to make dynamic iFrame height?

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.

Upvotes: 0

Views: 1783

Answers (2)

Alex Pineda
Alex Pineda

Reputation: 3039

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"

Upvotes: 1

sergio
sergio

Reputation: 5260

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>

Upvotes: 1

Related Questions