JavaScript, programming

Dynamically re-size an iFrame’s height across browsers

A while back I had a need to dynamically re-size an iFrame’s height and found a solution using a jQuery plug-in called autoHeight.  What I later found was that this solution provided poor results with Internet explorer when my iFrame’s contents were fairly large and frequently changing (i.e. via navigation inside the iFrame).

It took quite a bit of tinkering but I was able to come up with a solution that works (and works well) in IE, Firefox, Safari and Chrome.  It still uses jQuery but doesn’t depend on a plug-in.  Here’s the code in case you’re looking for the same thing:

First, the iFrame…

<iframe src="Page1.htm" id="MyFrame" 
frameborder="0" marginheight="0" marginwidth="0" 
width="800px" height="100px" scrolling="no"></iframe>

Next, the JavaScript to resize it…

<script type="text/javascript">
 
     function sizeFrame() {
          jQuery("#MyFrame", top.document).css({ height: 0 });
          var heightDiv = jQuery("#MyFrame", top.document).contents().find('body').attr('scrollHeight');
          jQuery("#MyFrame", top.document).css({ height: heightDiv });
     }
 
     jQuery(function() {
          sizeFrame();
          jQuery("#MyFrame").load(sizeFrame);            
     });
 
</script>

This line is needed to initially initialize the height so that it works in Safari and Chrome. Without this line the window will never shrink to fit smaller content, it will just retain the last biggest height.

jQuery("#MyFrame", top.document).css({ height: 0 });

6 thoughts on “Dynamically re-size an iFrame’s height across browsers

  1. i love this snippet; however, sometimes it makes the iframe too big. seems to be randomly.

  2. Each frame would have their own ID. So You may have Id=”MyFrame” for the first iFrame, and Id=”MyOtherFrame” for a second one.

    Then, in the jQuery, you would add additional code to manipulate the second iFrame, but instead of targeting #MyFrame you would target #MyOtherFrame.

    Contact me via the form if you need additional help.

Leave a Reply

Your email address will not be published. Required fields are marked *