My webpage contains an iframe that loads content dynamically, and I want to center it on the page based on its height. The issue I'm facing is that while my code works well for increasing content heights, it fails to recognize when the content size decreases.
The JavaScript functions properly when the content height increases, but fails to adjust when it decreases.
For example, if the initial page height is 400px and then changes to 420px, my code correctly identifies the new height. However, if the content subsequently shrinks to 350px, the code still maintains a reference to the previous height of 420px instead of updating to the new value. How can I resolve this issue?
Code:
function place()
{
var w = $(window).width();
w -= 1000;
w /= 2;
if(w < 12)
w = 12;
$("#div").css("left",""+w+"px");
$("#closeDiv").css("left",""+(w-12)+"px");
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;
$("#div").css("top",""+h+"px");
$("#div").css("height",""+ifh+"px");
$("#closeDiv").css("top",""+(h-12)+"px");
}
Even after content height reduces, the document title and .offsetHeight attributes continue showing the old height (e.g., 420px), rather than adjusting to the current smaller size.
Thank you for your assistance!
SOLUTION UPDATE
I utilized the solution provided in the answer I marked as correct, which was instrumental in resolving this issue. However, upon further investigation, I discovered that the root cause of the problem was that I had set the iframe's height to 100% of its container element. Surprisingly, changing it to 99% fixed the problem, although I don't fully understand why.
Thank you all for your support!