grec0o grec0o - 3 months ago 14
jQuery Question

Auto Resize not working

I have an Iframe and the content of this iframe changes so the window can be bigger or smaller so I added an auto resize script.

This script Works perfectly but only when the content is bigger, if the content changes and it is smaller than the last time, the window don't resize and the heigth is the same.

I don't know what is wrong. If you have any idea would be good.

Also there is my script and my iframe:

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";
}

$(function(){
var f=$('#foo')
f.load(function(){
f.contents().find("body").on('click', function(event) {
runAfterTimeout('foo');
});
})
})
function runAfterTimeout(id) {
setTimeout(function(){
autoResize(id);
},1000);
};


My iframe:

<iframe height="300px" width="100%" id="foo" src="" style="border: 0px currentColor; border-image: none;" onload="autoResize('foo')"></iframe>

Answer

I think you need to reset the height of the iframe each time onload is called. try this:

function autoResize(id){
    document.getElementById(id).height="0px";
    var newheight=document.getElementById(id).contentWindow.document.body.scrollHeight;
    var newwidth=document.getElementById(id).contentWindow.document.body.scrollWidth;

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