So I was fooling with an iframed forum today and had to figure out how to make the iframe resize to the height of its content, just to keep things pretty. This can be done rather easily with a little javascript.
Step 1:
Create your iframe and attach a function to the document.
1 2 3 4 5 6 | <iframe id="forum-iframe1" width="100%" frameborder="0" src="mypage.html"></iframe> <script> window.resizeiframe1 = function(height){ document.getElementById('forum-iframe1').style.height=(height+40)+'px'; } </script> |
Step 2:
Add code to iframed page (mypage.html) to get the document’s height and send it back to the resize function attached to the iframe’s parent document once the iframe is loaded.
1 2 3 4 5 6 7 8 9 10 11 12 13 | <html> <head> <script type="text/javascript"> function getHeight(){ var height = (document.documentElement.clientHeight || document.body.clientHeight); window.parent.resizeiframe1(height); } </script> </head> <body id="iframe-body" onload="getHeight()"> <table height="500"><tr><td>my content here</td></tr></table> </body> </html> |
Alternatively, if you use a javascript framework, such as prototype, its even easier. Here is my example using prototype:
Step 1:
Create your iframe and attach a function to the document.
1 2 3 4 5 6 | <iframe id="forum-iframe2" width="100%" frameborder="0" src="mypage-prototype.html"></iframe> <script> window.resizeiframe2 = function(height){ $('forum-iframe2').setStyle({'height':(height+40)+'px'}); } </script> |
Step 2:
Add code to iframed page (mypage.html) to get the document’s height and send it back to the resize function attached to the iframe’s parent document once the iframe is loaded.
1 2 3 4 5 6 7 8 | <html> <head> <script type="text/javascript" src="prototype.js"></script> </head> <body id="iframe-body" onload="window.parent.resizeiframe2($('iframe-body').getHeight());"> <table height="500"><tr><td>my content here</td></tr></table> </body> </html> |