Dynamically Resize an IFrame According to its contents

Published Tuesday, November 25, 2008 4:30 AM

problem with iframe is that you can't always predict the size of the content and eventually you'd end up with a scrollbar or even less convenient: a hidden part of the Iframe content

this is a straight forward, easy way to make sure that the IFrame is properly resized according to the contents of the page loaded inside the Iframe.

 

this will rely on the browser itself measuring the content width and height

this can be done by using the document.body.scrollHeight and document.body.scrollWidth properties which work the same way in all browsers IE and firefox

 

just to make sure that these properties work properly we'll set the initial width and height of the Iframe to 1 pixel so we can have a scroll bar to measure. if it's larger than that the scroll bars won't measure the whole width and height of the document and if it's 0 the reported scroll Area will be also Zero

 

body

one more issue to target is the margins. because we're using a subsection of the document which has the scroll Area Body does not include margins in that case we need to neutralize the effect of margins on the page. this can be done easily by setting the margins of the page to zero

 

resulting code would be in the Container page :

<iframe id="frameName" 
src="frame.html" width="1" height="1" 
frameborder="0" marginheight="0" marginwidth="0" 
scrolling="no"></iframe>

 

note that i have added the scrolling="no" attribute to make sure that there's no scrollbars displayed and i have also neutralized the border size by frameborder="0"

 

inner page would be like this in the End of the <body> i have added this simple javascrip

 

function doFrame(){            
    parent.document.getElementById("frameName").width= document.body.scrollWidth;
    parent.document.getElementById("frameName").height= document.body.scrollHeight;
}
doFrame();

 

note how i reference the frame by its Id.

 

Filed under: ,

Comments

# DotNetKicks.com said on Tuesday, November 25, 2008 4:54 AM

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Leave a Comment

(required) 
(required) 
(optional)
(required) 

This Blog

Syndication