user2812028
user2812028

Reputation: 263

Resize iFrame Content Via JavaScript

I am wondering if theres some way to make it so that if there is a bunch of content in an iFrame it will just resize the document essentially so it fits. Making all the content inside the iFrame smaller. To clarify I want to resize the content, not the iFrame's size itself.

Any ideas how I would do this?

I have tried out some stuff but so far no luck.

Script:

<script type="text/javascript">
function autoResize(id){
    var newheight;
    var newwidth;

    if(document.getElementById){
        newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
    }

    document.getElementById(id).height= (newheight) + "px";
    document.getElementById(id).width= (newwidth) + "px";
}
</script>

iFrame:

<iframe id="iframehtml" style="width:100%;height:100%;" onLoad="autoResize('iframe1');"></iframe>

By the way the reason there is no src set for the iFrame is because I have it in JavaScript so when you click a a button it will edit the html of the iFrame via jQuery.

Upvotes: 1

Views: 860

Answers (2)

DarthTux
DarthTux

Reputation: 156

You can use load event to resize iframe

var iframe = document.getElementByID('your-iframe');
iframe.addEventListener('load', function() {
  iframe.style.height = iframe.contentWindow.document.body.offsetHeight + 'px';
})

Upvotes: 1

unclemeat
unclemeat

Reputation: 5207

You should be able to achieve this using jQuery .contents() -

assuming id is the id of the element you wish to change within the iframe:

var frame = $('#iframehtml')
frame.contents().find(id).width = (newheight) + "px";

See http://forum.jquery.com/topic/changing-elements-in-an-iframe

Upvotes: 0

Related Questions