Resize iframe based on Content

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

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;
<iframe id="iframe1" name="iframe1" src="..." width="100%" frameborder="0" scrolling="no" onload="resizeIframeHeight('iframe1')"></iframe>
User avatar
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK

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

[syntax=javascript]<script type="text/javascript">
window.addEventListener('load', function(event){
var frame = document.getElementById('frame');

frame.addEventListener('load', function(event){ = this.contentDocument.body.offsetHeight + 35 + 'px';

<iframe id="frame" src=""></iframe>[/syntax]

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