Page 1 of 1

Resize iframe based on Content

Posted: Sun Jan 13, 2013 7:31 pm
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.
[syntax=javascript]
<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>
[/syntax]

Re: Resize iframe based on Content

Posted: Tue Jan 29, 2013 7:39 am
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

[syntax=javascript]<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>[/syntax]

I've never used contentDocument before so I'm assuming that is the correct use :)