David David - 4 months ago 11x
Javascript Question

How to get height of iframe contents as it changes?

I have an iframe that loads in a page from my website and I need to set it's positioning to the center of the page dynamically based on the height of the iframe's content, and I have had no issues with the code that I am using except that the height of the iframe's content will never return a value lower than what it is if the content get's smaller (if that makes sense).

The js recognizes when the content height grows, but not when it shrinks.

E.g. if I have a page that is 400px high, and then some content dynamically changes to 420px, my code will recognize that it is 420px high, but then if it changes to 350px, for instance, my code will still see it as being 420px high. How do I fix this?


function place()
var w = $(window).width();
w = 12;

var h = $(window).height();
var ifh = document.getElementById("inner").contentWindow.document.body.scrollHeight;
document.title = ifh;
h -= ifh;
h /= 2;
if(h < 20)
h = 20;

The document title continues to show the 420px, even when I know that the content is less than that. The same problem occurs for

Thanks for your help!


Okay, so I used the code in the answer I marked as solving the problem, as I did use it and it deserves credit for helping me solve this problem, but the actual problem that was involved here was that I had the height of the iframe set to be 100% of the container box; as soon as I set it to 99%, that fixed the problem. Not sure why...but hey!

Thanks for all of your help!


Try something like:

var iHeight;
if ($("iframe").length > 0) iHeight = $($("iframe")[0].contentDocument || $("iframe")[0].contentWindow.document).height();

Although good old fashioned ele call should work:

var iHeight;
if ($("iframe").length > 0) iHeight = $("iframe").height();