Resize Iframe On Content Refresh Or Update
I have an iframe that I would like to resize to match its contents whenever the contents auto refreshes (every few minutes) or when the user interacts with it. Although the conten
Solution 1:
What you need to do is to set a timer and check the iFrame size after a few moments. You may have to check several times as not all browsers return the correct size immediately.
This method works only on same-domain iFrames.
Bind a function to the iFrame onload event and when it executes check the height of the iFrame. If no height is found schedule another check in a few moments.
var iFrameSizeCount = 0;
var onloadFunction = function(event){
var contentHeight = document.getElementById('iFrameId').contentWindow.document.body.offsetHeight;
if(contentHeight == 0){
// Schedule a recheck in a few moments
iFrameSizeCount++; // we keep a count of how many times we loop just in caseif(iFrameSizeCount < 10){ // after a while we have to stop checking and call it a failsetTimeout(function(){ onloadFunction(event); }, 200);
returnfalse;
}
else {
contentHeight = 100; // eventually if the check fails, default to a fixed height. You could possibly turn scrolling to auto/yes here to give the iFrame scrollbars.
}
}
contentHeight += 30; // add some extra padding (some browsers give a height that's slightly too short)document.getElementById('iFrameId').style.height = contentHeight + 'px';
}
Then bind the event to the onload event of your iFrame (however you want to):
The "scrolling=auto" is useful, just in case the sizing fails at least they have scrollbars. The onload event fires if the iFrame reloads, so is useful if they've clicked a link inside it.
Solution 2:
I have had good luck with this jQuery plugin - https://github.com/davidjbradshaw/iframe-resizer
Post a Comment for "Resize Iframe On Content Refresh Or Update"