Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize iframe height according to content height [duplicate]

I'm trying to resize an iframe according to height and width of it's content(webpage). I've used a code that I found on stack's other answer. For setup of new width, it seems that works but I can't get that height to work and I don't know why.

You can see and edit my example here: http://jsfiddle.net/dzorz/pvtr3/

Here is my HTML:

<iframe id="finance-iframe" class="finance-iframe" src="http://wordpress.org" width="100%" height="300px" marginheight="0" frameborder="0" onLoad="autoResize('finance-iframe');"></iframe>

and javascript:

function autoResize("finance-iframe"){
  var newheight;
  var newwidth;

  if(document.getElementById){
    newheight=document.getElementById("finance-iframe").contentWindow.document.body.scrollHeight;
    newwidth=document.getElementById("finance-iframe").contentWindow.document.body.scrollWidth;
  }

  document.getElementById("finance-iframe").height= (newheight) + "px";
  document.getElementById("finance-iframe").width= (newwidth) + "px";
}

What am I doing wrong?

like image 298
dzordz Avatar asked Dec 09 '22 12:12

dzordz


1 Answers

There are 4 different properties to look into to get the height of the content in an iFrame.

document.documentElement.scrollHeight
document.documentElement.offsetHeight
document.body.scrollHeight
document.body.offsetHeight

Sadly they can all give different answers and these are inconsistent between browsers. If you set the body margin to 0 then the document.body.offsetHeight gives the best answer. To get the correct value try this function; which is taken from the iframe-resizer library that also looks after keeping the iFrame the correct size when the content changes,or the browser is resized.

function getIFrameHeight(){
    function getComputedBodyStyle(prop) {
        function getPixelValue(value) {
            var PIXEL = /^\d+(px)?$/i;

            if (PIXEL.test(value)) {
                return parseInt(value,base);
            }

            var 
                style = el.style.left,
                runtimeStyle = el.runtimeStyle.left;

            el.runtimeStyle.left = el.currentStyle.left;
            el.style.left = value || 0;
            value = el.style.pixelLeft;
            el.style.left = style;
            el.runtimeStyle.left = runtimeStyle;

            return value;
        }

        var 
            el = document.body,
            retVal = 0;

        if (document.defaultView && document.defaultView.getComputedStyle) {
            retVal =  document.defaultView.getComputedStyle(el, null)[prop];
        } else {//IE8 & below
            retVal =  getPixelValue(el.currentStyle[prop]);
        } 

        return parseInt(retVal,10);
    }

    return document.body.offsetHeight +
        getComputedBodyStyle('marginTop') +
        getComputedBodyStyle('marginBottom');
}
like image 164
user3426858 Avatar answered Dec 15 '22 00:12

user3426858