Aug 04

While iframes are not good to use normaly, I use it to mix different server side languages. (eg: pulling through perl/ASP scripts to display on a php page). Please only use this for non indexed (admin/managemt/report) pages because iframes are no good for SEO.

Javascript for the parent page,

//this uses mootools. This code should be placed inside domready or load event of the window
$('my-iframe').addEvent('load',function()
{	innerDoc = ($('my-iframe').contentDocument) ? $('my-iframe').contentDocument : $('my-iframe').contentWindow.document;
	objToResize = ($('my-iframe').style) ? $('my-iframe').style : $('my-iframe');
	objToResize.height = (innerDoc.body.scrollHeight + 50) + 'px';
	objToResize.width = (innerDoc.body.scrollWidth + 20) + 'px';
	window.scrollTo(0, 0);//optional code to scroll the parent window back to top
});

And the iframe should look like this,

<iframe id="my-iframe" src="my_page_to_iframe.php" frameborder="0" scrolling="auto" ></iframe>

Thats it! If the sites are on two domains, take a look at this post to get around that.

5 Responses to “Resize iframe to fit content (all code in parent window)”

  1. ESL Says:

    Hey guys, My name is Fiona Choo and I am now in Hawaii. Has anybody stumbled upon any website that is quite the same as this ESL instructional site. I have no budget whatsoever, please let me have more information on any such free sites. Much appreciated.

  2. Margy Hannen Says:

    I was browsing the web and came across your website. I really enjoyed reviewing your posts and will be back to interact with your community.

  3. maxhb Says:

    Really cute solution! Sadly this method fails if the content of the iframe is delivered by a foreign server. This will result in “Permission denied to access property ‘body’”. Any idea how to solve the resizing problem in situations like that?!

  4. Jim Says:

    Hi! I work for a long time in web, games, web development and if you need any help or have any questions shoot me a message: welcome at lezgro.com. Ask for Jim. Glad to help.

  5. SEM Says:

    Really informative article post.Really looking forward to read more. Fantastic.

Leave a Reply