Click here to Skip to main content
15,880,427 members
Articles / Web Development / HTML

How To Adjust IFrame Height on Its Content

Rate me:
Please Sign up or sign in to vote.
4.27/5 (12 votes)
6 Jul 2007 195.8K   22   13
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:

HTML
<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:

JavaScript
 <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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Ukraine Ukraine
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralGreat Job Pin
Member 39633857-Jul-09 5:09
Member 39633857-Jul-09 5:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.