Automatically sizing an inline frame

Monday, September 29, 2008 21:22
Posted in category Web

It’s just an annoyance I run into every now and then; you define an inline frame in an HTML page, but for some reason it just won’t automatically adjust to the size of the content.

Here’s the fix I tend to use.

Insert this code somewhere between the <head> and </head> tags of your HTML document;

 

<script type="text/javascript">
function sizeIFrame(frameId){
try{
frame = document.getElementById(frameId);
innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
objToResize = (frame.style) ? frame.style : frame;
objToResize.height = innerDoc.body.scrollHeight + 10;
}
catch(err){
alert(err.message);
}
}
</script>

 Put this in the <iframe> declaration tag;

onload="if (window.parent && window.parent.sizeIFrame) {window.parent.sizeIFrame('myIFrame');}"

So that your IFRAME might look like this;

<iframe id="myIFrame" name="myIFrame" onload="if (window.parent && window.parent.sizeIFrame) {window.parent.sizeIFrame('myIFrame');}">
Not supported error.
</iframe>
That’s it.

You can leave a response, or trackback from your own site.
Tags: ,

Leave a Reply

You must be logged in to post a comment.