Posted By

dubogii on 05/17/11


Tagged

iframe resize


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

jillella


Resize iFrame to Fit Content (Same Domain Only)


 / Published in: jQuery
 

URL: http://css-tricks.com/snippets/jquery/fit-iframe-to-content/

Still problematic...

  1. The source of the iframe content must reside on the same domain
  2. if the content inside the iframe changes height, this won't adapt
  3. I left Google Analytics code off the demo above, as when I added it in it seems to interfere and not resize the iframe, despite seemingly generating no errors.
  1. Normally you set and width and height for iframes. If the content inside is bigger, scrollbars have to suffice. The script below attempts to fix that by dynamically resizing the iframe to fit the content it loads.
  2.  
  3.  
  4.  
  5. <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
  6. <script type='text/javascript'>
  7.  
  8. $(function(){
  9.  
  10. var iFrames = $('iframe');
  11.  
  12. function iResize() {
  13.  
  14. for (var i = 0, j = iFrames.length; i < j; i++) {
  15. iFrames[i].style.height = iFrames[i].contentWindow.document.body.offsetHeight + 'px';}
  16. }
  17.  
  18. if ($.browser.safari || $.browser.opera) {
  19.  
  20. iFrames.load(function(){
  21. setTimeout(iResize, 0);
  22. });
  23.  
  24. for (var i = 0, j = iFrames.length; i < j; i++) {
  25. var iSource = iFrames[i].src;
  26. iFrames[i].src = '';
  27. iFrames[i].src = iSource;
  28. }
  29.  
  30. } else {
  31. iFrames.load(function() {
  32. this.style.height = this.contentWindow.document.body.offsetHeight + 'px';
  33. });
  34. }
  35.  
  36. });
  37.  
  38. </script>
  39.  
  40.  
  41.  
  42. Will resize an iframe like this:
  43.  
  44. <iframe src="content.html" class="iframe" scrolling="no" frameborder="0"></iframe>

Report this snippet  

You need to login to post a comment.