Skip to content
Advertisement

Resizing ‘iframe’ after inside content is loaded

I have an iFrame in which I am loading a page which uses ajax to load data after various page labels are clicked. Now I am using Javascript function to calculate loaded-data height for replacing iframe’s height which results into resizing iframe and thus avoids scrollbars. Now my problem is script gets called as soon as labels are clicked, but data is still loading. Kindly tell me something I can use to wait till ajax is finished loading data and then calling my function.

I am using the following script:

function resizeFrame() {
    var body = document.body,
    html = document.documentElement;
    var iFrame = parent.document.getElementById("iframe1");//get id of iframe from parent
    var nHeight=0;
    var iframeWin = iFrame.contentWindow.document.body ;
    nHeight = iframeWin.scrollHeight;
    iFrame.style.height = nHeight+'px'; //set the frame height to correspond to the content 
}

and my html is as following:

<iframe src="" id="iframe1" name="iframe1" scrolling="no" frameborder="0" onload="$(document).ready(function(){resizeFrame();});"  style="width:960px;height:570px">

The above code works fine for me (iframe/src url both are in same domain.) I also want to get the height of a div element which is in iframe content window page. How do I grab that?

Advertisement

Answer

html

<iframe id="containter-frame" 
        src="<url of the page>"
        frameborder="0"
        min-height="600px"
        width="100%">
</iframe>

javascript/jquery:

$(document).ready(function(){

    var frame = $('iframe#containter-frame');

    //hide document default scroll-bar
    document.body.style.overflow = 'hidden';


    frame.load(resizeIframe);   //wait for the frame to load
    $(window).resize(resizeIframe); 

    function resizeIframe() {
        var w, h;       

        //detect browser dimensions
            if($.browser.mozilla){
            h = $(window).height();
            w = $(window).width();                  
        }else{
            h = $(document).height();
            w = $(document).width();
        }

        //set new dimensions for the iframe
            frame.height(h);
        frame.width(w);
    }
});

The trick here is frame.load method waits for the frame to load. After that the height and width is manipulated as required. Here i am setting is to cover whole of the screen. And the page contains only a iframe and nothing else.

Kind Regards.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement