Search code examples
javascriptiframe

Resizing an iFrame to fit contents by obtaining the scrollHeight (javascript)


I am trying to resize the iframe to fit content. After seeing how others have done it I thought the simplest way was to get the scrollHeight of the iframe and resize the iframe accordingly. I use onload in the iframe tag to run this. I have composed dozens of variations on this theme with no success.

 function resizeIFrame(){

     var sHeight, frame;

      frame = document.getElementById("bigFrame");
      sHeight = frame.scrollHeight;
      frame.style.height = sHeight + 'px';
    }

When I alert out the sHeight variable I get the height of the frame and not the scrollHeight. This indicates that I may not be collecting the scrollHeight correctly.

I know this question may be similar to many previously but there are many ways to approach this problem and a wider variety of answers. I would like to know what is wrong with this approach to resizing iframes to fit content?

This is the html.

   <div id="contentContainer">
       <iframe id="bigFrame" 
                src="home/home.html" 
                name="mainFrame"     
                onload="resizeIFrame()" 
                onresize="resizeIFrame()" 
                scrolling="no" 
                seamless;  >
            </iframe>
   </div>

Solution

  • Ok I got this to work perfectly.
    Adding - contentWindow.document.body.scrollHeight - enabled me to get the scrollHeight. I was trying to get the scrollHeight from a variable. This didn't work. What worked was to get the scrollHeight direct from the document.

    I had to add some space at the bottom of each page. Thus the +80;. Unfortunately this only added 80 every time the function was invoked. Resetting the frame height to 0px before readjusting solved the problem.

    So there you go. This function resizes an iframe to fit its content by getting the scrollHeight and setting the iframes height to match.

     function resizeIFrame(){
    
            var sHeight, frame;
    
               frame = document.getElementById("bigFrame");
               frame.style.height = '0px';
               sHeight = document.getElementById('bigFrame').
                      contentWindow.document.body.scrollHeight + 80;
               frame.style.height = sHeight + 'px';
         }