Resize iframe based on Content

JavaScript related questions should go here.
Post Reply
User avatar
exload
Posts: 9
Joined: Mon Oct 29, 2012 4:32 am
Contact:

Resize iframe based on Content

Post by exload »

No matter what I do I cannot seem to get this to work properly! All I want to do is simply adjust an iframe's size based on the content it loads. This is what I have at the moment. Any suggestions or help on how to get this to work? Also I want to use javascript and avoid jquery.
<script type="text/javascript" language="JavaScript">
<!--
function resizeIframeHeight(e){
    if (e.Document && e.Document.body.scrollHeight)
        e.width = e.contentWindow.document.body.scrollHeight;
    else if (e.contentDocument && e.contentDocument.body.scrollHeight)
        e.width = e.contentDocument.body.scrollHeight + 35;
    else (e.contentDocument && e.contentDocument.body.offsetHeight)
        e.width = e.contentDocument.body.offsetHeight + 35;
}
//-->
</script>
<iframe id="iframe1" name="iframe1" src="..." width="100%" frameborder="0" scrolling="no" onload="resizeIframeHeight('iframe1')"></iframe>
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: Resize iframe based on Content

Post by jacek »

Sorry for missing this thread... either way.

You are passing a string to the resizeIframeHeight() function and then treating it as an element which causes an error. Also I would try and stick to valid xhtml where possible. So something more like this
<script type="text/javascript">
    window.addEventListener('load', function(event){
        var frame = document.getElementById('frame');
        
        frame.addEventListener('load', function(event){
            this.style.width = this.contentDocument.body.offsetHeight + 35 + 'px';
        });
    });
</script>

<iframe id="frame" src="http://website.com/"></iframe>
I've never used contentDocument before so I'm assuming that is the correct use :)
Image
Post Reply