JavaScript Document (8) Events (8) Strings (3)
Exchange Links About this site Links to us
|
Adjusting the height of an IFRAME according to its content
7 comments. Current rating: (2 votes). Leave comments and/ or rate it.
Question: On my page I display search results in an IFRAME. Sometimes there's only 5 rows of data, sometimes it can be 2000. I need to have the IFRAME size adjust to the number of elements. I was working with a construct like
iframe_1.height = 30 + 16 * (number_of_rows)
but this estimating formula relies on a certain font size. And it looks really wrong in Netscape or Opera.
Answer: Why estimate if you can make an exact calculation of the document height? Take the code below which will work on Internet Explorer and various Netscape versions.
 | |  | | <script type="text/javascript">
function adjustIFrameSize (iframeWindow) {
if (iframeWindow.document.height) {
var iframeElement = parent.document.getElementById(iframeWindow.name);
iframeElement.style.height = iframeWindow.document.height + 'px';
iframeElement.style.width = iframeWindow.document.width + 'px';
}
else if (document.all) {
var iframeElement = parent.document.all[iframeWindow.name];
if (iframeWindow.document.compatMode &&
iframeWindow.document.compatMode != 'BackCompat')
{
iframeElement.style.height =
iframeWindow.document.documentElement.scrollHeight + 5 + 'px';
iframeElement.style.width =
iframeWindow.document.documentElement.scrollWidth + 5 + 'px';
}
else {
iframeElement.style.height = iframeWindow.document.body.scrollHeight + 5 + 'px';
iframeElement.style.width = iframeWindow.document.body.scrollWidth + 5 + 'px';
}
}
}
</script>
| |  | |  |
Comments:
|
|
|
|
I assume we paste this code into the head of our html document, and it will automatically apply to all iframes?
Thanks
|
|
|
|
|
Does this work for external pages (from different website) as well? Maybe I'm doing something wrong here...
Thanks,
Konrad
|
|
|
|
|
No exactly where i am looking for
Thanks anyway
|
|
|
|
|
Works perfectly for my situation - thank you
|
2008-04-09, 09:52:11 (updated: 2008-04-09, 09:52:50) |
|
|
|
|
|
|
|
|
From where should be called this adjustIFrameSize() method? From the <body onload=... />?
Another question is about
iframeWindow.document.documentElement.scrollHeight + 5 + 'px';
How was infered this value of 5 in the above code?
Thank you
|
|
|
|
|
Should I paste that code onto the page that has the iFrame, or the page that is going to be INSIDE the iframe? You didn't make it quite clear about where to put the code...
|
|