views:

50

answers:

1

I have an iframe embedded within my page - it's just part of my page, not the whole thing. I am reloading the iframe dynamically and want it to resize according to the height of the content within it.

The content is on the same domain, so (hopefully?) no need for a solution as complex as that given in Resizing an iframe based on content.

This is the code I'm using to resize it, but it isn't working. The frame reloads OK, but the height always stays the same. Can anyone advise?

I've also tried the top solution in How to autosize an iframe without any luck.

I think it could be because the page inside the iframe takes a while to load, so it hasn't finished loading by the time the height is set. Maybe.

<iframe frameborder=0 border=0 src="" width="100%" height="400px" name="commentframe" id="commentframe"></iframe>
function reload_frame(uid) {
    document.getElementById('commentframe').src = "comments.html?" + uid;
    document.getElementById('commentframe').height = document.getElementById('commentframe').contentWindow.document.body.scrollHeight + "px";
}

Update:

Trying, with no luck:

<iframe frameborder=0 border=0 src="" width="100%" height="400px" name="commentframe" id="commentframe" onload="reload_frame()"></iframe>
function reload_frame() {
        var commentframe = document.getElementById('commentframe');
        commentframe.style.height = (commentframe.scrollHeight + 10).toString() + "px";
}

It does resize the iframe, but only to +10px of its original height - if the content is longer than this, it is still hidden.

Maybe I need an onload event inside the body of the iframe itself?

+1  A: 
<script type="text/javascript">
    function ajustHeight() {
        $("#myIframe").parent()[0].style.height = ($("#myIframe")[0].scrollHeight + 150).toString() + "px";
    }
</script>
<iframe id="myIframe" src="mypage.html" width="100%" height="100%" onload="ajustHeight()"></iframe>
Zote
why +150? what are we expecting to happen here?
lincolnk
Thank you! Is there a way to write it in normal Javascript, without jquery? I'm just trying to translate...
AP257
What does the parent() call do? My iframe isn't inside a containing div (and please note, it's not the only thing on the page...), so what exactly is having its height set?
AP257
@lincolnk and @AP257 sorry, I just did copy and paste from my site...
Zote
no worries. just need to figure out how to use it for an iframe without a parent?
AP257
try $("#myIframe")[0].style.height = $("#myIframe")[0].scrollHeight.toString() + "px";
Zote
alas, no luck (see update)
AP257