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%;
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.
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 to0
pixels in height if it is to shrink below the defaultiframe
height in some browsers.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.
You just need to apply your code on the iframe
load
event, so the height is already known at that time, code follows: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:
Adjust height of an iframe, on load and resize, based on its body height.
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?
Just do it on the HTML tag, works perfect