There are occasions where you may want
an IFrame to fit its content. For example, you may not want the IFrames
scrollbars to appear but would prefer to use the browsers windows
native scroll bars instead. This little script demonstrates how to
achieve that.
It is important to note that the
script is placed in the page that is being loaded into the IFrame.
Conceptually we need to capture the contents height and then resize the
IFrame to fit that height. Let's look at the script that will allow us
to do that;
The first thing we need to do is
create a series of variables to use later on in scripts. It is
important to note that an alternate approach could be employed here,
where the variables become arguments of the function and are set at the
event handler point. This would allow the user to set different speeds
or different offsets at each link. However, in most instances setting
global variables as I have done below would suffice.
1.function autofitIframe(id){ 2. if (!window.opera && !document.mimeType && document.all && document.getElementById){ 3. parent.document.getElementById(id).style.height=this.document.body.offsetHeight+"px"; 4. } 5. else if(document.getElementById) { 6. parent.document.getElementById(id).style.height=this.document.body.scrollHeight+"px" 7. } 8. } |
Line 1:Creates a
function called autofitIframe() and utilises an argument value of id.
The id argument will be used to identify the iframe that the content is
being loaded into.
Line 2:Defines a condition that allows only Internet Explorer based browsers that support the document.getElementById method.
Line 3:Begins by
referring to the parent document and then defining the IFrames id value
through an argument (that is later passed from an event handler) and
obtaining its current height. We then have the height of the iframe
equal the contents height with the this.document.body.offsetHeight+"px"
statement.
Line 4:Closing bracket for condition
Line 5:Creates a condition for standards based browsers.
Line 6:Is almost the
same as line 3 except here we use scrollHeight to capture the contents
height as opposed to offsetHeight. Moz, Safari, Opera etc seem to
prefer this method.
Line 7 & 8:Closing brackets for function.
The only thing left to do is call the
function and pass the id value of the iframe as an argument. For
example, if we have an iframe who's id value is contentFRM then the
onload event handler in the content page would like so;
onload="autofitIframe('contentFRM')"
That's all there really is to it. Hope this proves usefull for you guys in your development efforts.
Just a note, IE Mac doesnt support any of the methods used here.
Download Example
View Finished Example