13

I'm trying to resize an iframe dynamicly to fit its content. To do so I have a piece of code:

$("#IframeId").height($("#IframeId").contents().find("html").height());​

It doesnt work. Is it because of cross-domain issue? How do I get it to fit? Please take a look at Fiddle: JsFiddle

ps I have set the html and body of the link height:100%;

Nelson
  • 49,283
  • 8
  • 68
  • 81
Youss
  • 4,196
  • 12
  • 55
  • 109
  • I forgot to mention that on the url:moskah/links you can save links like: http://facebook.com Please try it, you will than understand the list will get bigger and bigger – Youss Oct 13 '12 at 10:56
  • See also this way with simple javascript: http://stackoverflow.com/questions/9162933/make-iframe-height-dynamic-based-on-content-inside-jquery-javascript/9163087#9163087 – Aristos Mar 19 '13 at 00:13

7 Answers7

18

You just need to apply your code on the iframe load event, so the height is already known at that time, code follows:

$("#IframeId").load(function() {
    $(this).height( $(this).contents().find("body").height() );
});

See working demo . This demo works on jsfiddle as I've set the iframe url to a url in the same domain as the jsfiddle result iframe, that is, the fiddle.jshell.net domain.

UPDATE:
@Youss: It seems your page for a strange reason don't get the body height right, so try using the height of the main elements instead, like this:

$(document).ready(function() {
    $("#IframeId").load(function() {
            var h = $(this).contents().find("ul.jq-text").height();
            h += $(this).contents().find("#form1").height();
            $(this).height( h );
        });
});
Nelson
  • 49,283
  • 8
  • 68
  • 81
  • Hi, it doesnt work for me...take a look http://moskah.nl/er.html Its all on the same domain moskah.nl – Youss Oct 13 '12 at 11:32
  • 1
    This does work for me in the browsers I have installed, that is chrome 22 and firefox 15 , I haven't test IE, thanks for reporting. – Nelson Oct 13 '12 at 11:34
  • @Youss You are not using the load event as my code has, please see the update to my answer and paste that same code replacing yours. – Nelson Oct 13 '12 at 11:38
  • @Nelson No sorry, take a look at course code you will see I placed your code: http://moskah.nl/er.html – Youss Oct 13 '12 at 11:42
  • IE doesn't fire the `load` event after it has already been loaded like FF and Chrome do. Try using `ready`. – Niels Oct 13 '12 at 11:54
  • 1
    @Youss It seems for some strange reason your links.html page dont report the body height right, try using the workaround I put in my update. – Nelson Oct 13 '12 at 11:57
  • @Youss Btw it was me that added those example garbage links to test this. – Nelson Oct 13 '12 at 12:04
4

Not sure why @Nelson's solution wasn't working in Firefox 26 (Ubuntu), but the following Javascript-jQuery solution seems to work in Chromium and Firefox.

/**
 * Called to resize a given iframe.
 *
 * @param frame The iframe to resize.
 */
function resize( frame ) {
  var b = frame.contentWindow.document.body || frame.contentDocument.body,
      cHeight = $(b).height();

  if( frame.oHeight !== cHeight ) {
    $(frame).height( 0 );
    frame.style.height = 0;

    $(frame).height( cHeight );
    frame.style.height = cHeight + "px";

    frame.oHeight = cHeight;
  }

  // Call again to check whether the content height has changed.
  setTimeout( function() { resize( frame ); }, 250 );
}

/**
 * Resizes all the iframe objects on the current page. This is called when
 * the page is loaded. For some reason using jQuery to trigger on loading
 * the iframe does not work in Firefox 26.
 */
window.onload = function() {
  var frame,
      frames = document.getElementsByTagName( 'iframe' ),
      i = frames.length - 1;

  while( i >= 0 ) {
    frame = frames[i];
    frame.onload = resize( frame );

    i -= 1;
  }
};

This continually resizes all iframes on a given page.

Tested with jQuery 1.10.2.

Using $('iframe').on( 'load', ... would only work intermittently. Note that the size must initially be set to 0 pixels in height if it is to shrink below the default iframe height in some browsers.

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
3

What you can do is the following:

  • Within the iFrame use document.parent.setHeight(myheight) to set the height within the iFrame to the parent. Which is allowed since it is a child control. Call a function from the parent.

  • Within the parent you make a function setHeight(iframeheight) which resizes the iFrame.

Also see:
How do I implement Cross Domain URL Access from an Iframe using Javascript?

Community
  • 1
  • 1
Niels
  • 48,601
  • 4
  • 62
  • 81
  • Hi, I dont really understand this, and it seems way to complicated. I was hoping just to alter the little code I have. Cross-browser is not really an issue because the iframe website is mine. I just mentioned it because it wouldn't work on JsFiddle (I should have explained this, my bad) – Youss Oct 13 '12 at 11:16
  • As I said, its the same domain (moskah.nl) – Youss Oct 13 '12 at 11:33
  • Why don't you use a PHP `include` or a ASP.NET `ContentPanel`? If I may ask? – Niels Oct 13 '12 at 11:44
  • Because I have no idea what that is:) And besides I think (no Im convinced) this can solved with just a few lines of code. I will post it when I find it – Youss Oct 13 '12 at 11:49
3

Just do it on the HTML tag, works perfect

$("#iframe").load(function() {
    $(this).height( $(this).contents().find("html").height() );
});
Roy Shoa
  • 3,117
  • 1
  • 37
  • 41
1

As the answer to the question use an already outdated jquery (load has been deprecated and replaced with .on('load',function(){}), below is the latest code for the answer in the question.

Note that I use the scrollHeight and scrollWidth, which I think will load much nicer than using Height and Width like the answer provided. It will totally fit, without scroll anymore.

$("#dreport_frame").on('load',function(){

  var h = $('#dreport_frame').contents().find("body").prop('scrollHeight');
  var w = $('#dreport_frame').contents().find("body").prop('scrollWidth');

  $('#dreport_frame').height(h);
  $('#dreport_frame').width(w);
})
maximran
  • 425
  • 4
  • 11
0

Adjust height of an iframe, on load and resize, based on its body height.

var iFrameID = document.getElementById('iframe2');
var iframeWin = iFrameID.contentWindow;

var eventList = ["load", "resize"];
for(event of eventList) {
    iframeWin.addEventListener(event, function(){ 
        if(iFrameID) {
            var h = iframeWin.document.body.offsetHeight  + "px";
            if(iFrameID.height == h) {
                return false;
            }

            iFrameID.height = "";
            iFrameID.height = iframeWin.document.body.offsetHeight  + "px";

        }   
    })  
} 
GarryOne
  • 1,430
  • 17
  • 21
0

At end, I come with this cross-domain solution that work also for resize... (resize not triggering : Auto resize iframe height when the height of the iframe contents change (same domain) )

Iframe :

(function() {
    "use strict";
    var oldIframeHeight = 0,
        currentHeight = 0;
    function doSize() {
        currentHeight = document.body.offsetHeight || document.body.scrollHeight;
        if (currentHeight !== oldIframeHeight) {
            console.log('currentHeight', currentHeight);
            window.parent.postMessage({height:currentHeight}, "*");
            oldIframeHeight = currentHeight;
        }
    }
    if (window.parent) {
        //window.addEventListener('load', doSize);
        //window.addEventListener('resize', doSize); 
        window.setInterval(doSize, 100); // Dispatch resize ! without bug
    }
})();

Parent page :

window.addEventListener('message', event => {
    if (event.origin.startsWith('https://mysite.fr') && event.data && event.data.height)  {
        console.log('event.data.height', event.data.height);
        jQuery('#frameId').height(event.data.height + 12);
    }
});
molokoloco
  • 4,504
  • 2
  • 33
  • 27