Setting Iframe height to its content height using Javascript

While loading an iframe on page the most difficult thing is to set it's height to the height of the content of the iframe. I looked around the web and got the code. This is pure Javascript, doesn't contain jQuery or any other libraries. Set these functions :

function getDocHeight(doc) {
    doc = doc || document;
    var body = doc.body, html = doc.documentElement;
    var height = Math.max( body.scrollHeight, body.offsetHeight,
        html.clientHeight, html.scrollHeight, html.offsetHeight );
    return height;
}
function setIframeHeight(id) {
    var ifrm = id;
    var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
    ifrm.style.visibility = 'hidden';
    ifrm.style.height = "10px"; // reset to minimal height in case going from longer to shorter doc
    // some IE versions need a bit added or scrollbar appears
    ifrm.style.height = getDocHeight( doc ) + 4 + "px";
    ifrm.style.visibility = 'visible';
}
Now add an event listener to the iframe :

onload='setIframeHeight(this)'
After adding the event listener, the iframe element will look like this :

<iframe onload="setIframeHeight(this)" src="ogroms.com"></iframe>
When the iframe completes loading the function will check it's content height and set the height of the iframe to it's content height. Pretty Neat, Huh ?

Comments

Popular posts from this blog

HOW TO REGISTER FOR SAFETOKEN

How To Get Help In MMM Nigeria - Mavrodi Mondial Moneybox