Gausie
Gausie

Reputation: 4359

How can I get an iframe to automatically resize whenever its "src" changes? (using jQuery)

I've written this code:

$('#main-content > iframe').load(function(){
    var $document = $(this.contentWindow.document);
    alert($document.height());
    $(this).height($document.height());
});

This works when the page first loads, but when the user changes the src of the iframe while using the page, it doesn't resize.

I change the src like this:

$('#main-content > iframe').attr("src",href);

No need to worry about XSS - it's all local.

Any suggestions?

Upvotes: 0

Views: 594

Answers (2)

Jared Farrish
Jared Farrish

Reputation: 49208

<script type="text/javascript">
$(document).ready(function(){
    $('#main-content > iframe').attr('src','onmouseclick.html');
    set();
});
function set() {
    $('#main-content > iframe').load(function(){
        var $document = $(this.contentWindow.document);
        //alert($document.height());
        $(this).height($document.height());
    });
}
</script>

<div id="main-content">
 <iframe id="main-contentiframe"></iframe>
 <a href="onmouseclick.html" onmouseover="$('#main-content > iframe').attr('src',this.href);set();return false;">Link</a>
 <a href="testscript.html" onmouseover="$('#main-content > iframe').attr('src',this.href);set();return false;">Link</a>
</div>

Upvotes: 2

Kristoffer Sall-Storgaard
Kristoffer Sall-Storgaard

Reputation: 10636

In Internet Explorer you can add an eventlistener to the onreadystatechange of iframes, in my experience it works more reliably than load

More information can be found at msdn

Example:

$('#main-content > iframe')[0].onreadystatechange = function(evt)
{
    if(window.event)
        evt = window.event;
    var $document = $(evt.srcElement);
    alert($document.height());
    $(this).height($document.height());
}

Beware, I have not tested the code

Upvotes: -1

Related Questions