65.9K
CodeProject is changing. Read more.
Home

How To Adjust IFrame Height on Its Content

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.27/5 (11 votes)

Jul 6, 2007

viewsIcon

197304

How to adjust an iFrame height to its content: tested in Mozilla, Opera, Internet Explorer

Introduction

Some browsers do not support all W3C standards and you will face a problem when you want to adjust IFrame height on its content using JavaScript. I have spent some hours experimenting with different DOM-objects and I have found quite a good solution for Mozilla, Internet Explorer and Opera browsers.

Using the Code

If you have IFrame in your HTML, the first step is to add onload handler as follows:

<iframe id='myFrame' 

frameborder=0 scrolling=no width=100%  

src="..."
    onload='adjustMyFrameSize

();'> 
</iframe> 

Then you need to place such a script BEFORE the IFrame element:

 <script type="text/javascript">
    
    function getElement(aID)
    {
        return (document.getElementById) ?
            document.getElementById(aID) : 

document.all[aID];
    }

    function getIFrameDocument(aID){ 
        var rv = null; 
        var frame=getElement(aID);
        // if contentDocument exists, W3C 

compliant (e.g. Mozilla) 
        if (frame.contentDocument)
            rv = frame.contentDocument;
        else // bad Internet Explorer  ;)
            rv = document.frames[aID].document;
        return rv;
    }

    function adjustMyFrameHeight()
    {
        var frame = getElement

("myFrame");
        var frameDoc = getIFrameDocument

("myFrame");
        frame.height = frameDoc.body.offsetHeight;
    }
</script> 

History

  • 6th July, 2007: Initial post