Tuesday, December 12, 2006

Let iframe auto-adjust its height

Iframe, especially no-border iframe, can integrate with a webpage seamlessly, and can update one part of this page without refresh. However, the size of a iframe usually can not adjust as arbitrarily as a layer. Now, we can use a javascript function below, to let iframe adjust its height automaticly.

function SetCwinHeight(){
  var cwin=document.getElementById("cwin");
  if (document.getElementById){
      if (cwin && !window.opera) {
          if (cwin.contentDocument && cwin.contentDocument.body.offsetHeight)
              cwin.height = cwin.contentDocument.body.offsetHeight;
          else if(cwin.Document && cwin.Document.body.scrollHeight)
              cwin.height = cwin.Document.body.scrollHeight;
      }
  }
}

Then, add html code of iframe. Donot foreget the attribute "onload". Of course, the id of iframe should match "cwin" in the function SetCwinHeight:

<iframe width="778" align="center" height="200" id="cwin" name="cwin" onload="Javascript:SetCwinHeight()" frameborder="0" scrolling="no"></iframe>

In the end, recommend a function used to get the object of a html element.

function GetObj(objName){
    if(document.getElementById){
        return eval('document.getElementById("' + objName + '")');
    }else if(document.layers){
        return eval("document.layers['" + objName +"']");
    }else{
        return eval('document.all.' + objName);
    }
}

5 comments:

Anonymous said...

Works like a charm. Thanks so much!

Anonymous said...

Works great in IE but not in firefox. Any idea?

Anonymous said...

works in ie only. tried firefox, safari, chrome.

Frank said...
This comment has been removed by the author.
Frank said...

its works only in same domain... but when we link to another domain its not working...