Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery get height of iframe content when loaded

I have a Help page, help.php that I am loading inside an iframe in main.php How can I get the height of this page once it has loaded in the iframe?

I am asking this because I can't style the height of to iframe to 100% or auto. That's why I think I need to use javascript.. I am using jQuery

CSS:

body {     margin: 0;     padding: 0; } .container {     width: 900px;     height: 100%;     margin: 0 auto;     background: silver; } .help-div {     display: none;     width: 850px;     height: 100%;     position: absolute;     top: 100px;     background: orange; } #help-frame {     width: 100%;     height: auto;     margin:0;     padding:0; } 

JS:

$(document).ready(function () {     $("a.open-help").click(function () {         $(".help-div").show();         return false;     }) }) 

HTML:

<div class='container'>     <!-- -->     <div class='help-div'>         <p>This is a div with an iframe loading the help page</p>         <iframe id="help-frame" src="../help.php" width="100%" height="100%" frameborder="1"></iframe>     </div>  <a class="open-help" href="#">open Help in iFrame</a>      <p>hello world</p>     <p>hello world</p>     <p>hello world</p>     <p>hello world</p>     <p>hello world</p> </div> 
like image 780
FFish Avatar asked Oct 02 '10 14:10

FFish


People also ask

How do I make my iframe height 100%?

To size the <iframe> , we ignore the width="560" height="315" element properties, and instead use the CSS properties width:100%;height:100%; . That's it: a full-width <iframe> with fixed aspect ratio.


1 Answers

ok I finally found a good solution:

$('iframe').load(function() {     this.style.height =     this.contentWindow.document.body.offsetHeight + 'px'; }); 

Because some browsers (older Safari and Opera) report onload completed before CSS renders you need to set a micro Timeout and blank out and reassign the iframe's src.

$('iframe').load(function() {     setTimeout(iResize, 50);     // Safari and Opera need a kick-start.     var iSource = document.getElementById('your-iframe-id').src;     document.getElementById('your-iframe-id').src = '';     document.getElementById('your-iframe-id').src = iSource; }); function iResize() {     document.getElementById('your-iframe-id').style.height =      document.getElementById('your-iframe-id').contentWindow.document.body.offsetHeight + 'px'; } 
like image 129
FFish Avatar answered Sep 18 '22 12:09

FFish