Monday, September 4, 2017
Setting Iframe height to its content height using Javascript
Setting Iframe height to its content height using Javascript
While loading an iframe on page the most difficult thing is to set its height to the height of the content of the iframe. I looked around the web and got the code. This is pure Javascript, doesnt contain jQuery or any other libraries. Set these functions :
function getDocHeight(doc) {Now add an event listener to the iframe :
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;
}
onload=setIframeHeight(this)After adding the event listener, the iframe element will look like this :
<iframe onload="setIframeHeight(this)" src="subins.html"></iframe>When the iframe completes loading the function will check its content height and set the height of the iframe to its content height. Pretty Neat, Huh ?
download file now
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.