views:

630

answers:

1

I have an iframe that can appear in a jQuery modal dialog, a popup window, or just as part of a page. The height of the content of this iframe can change as elements appear and disappear, and I need the containing iframe, along with the modal dialog or popup window where applicable, to change height as necessary to be 'just right' for the size of the content.

What's the best way to accomplish this? You can see the page where I need this behavior here.

Preferably there would be some event that will fire automatically if any content changes so I don't have to run some method everywhere that I make elements appear or disappear.

Thanks.

+1  A: 

I think you need to do something like

/* creating jQuery special event to catch DOM content change */
var changeInterval;

jQuery.fn.contentchange = function(fn) {
    return this.bind('contentchange', fn);
};

jQuery.event.special.contentchange = {
    setup: function(data, namespaces) {
        var self = this,
            $this = $(this),
            $originalContent = $this.html();
        changeInterval = setInterval(function(){
            if($originalContent != $this.html()) {
                    $originalContent = $this.html();
                    jQuery.event.special.contentchange.handler.call(self);
            }
        },500);
    },
    teardown: function(namespaces){
        clearInterval(changeInterval);
    },
    handler: function(event) {
        jQuery.event.handle.call(this, {type:'contentchange'})
    }
};
/* end */

/* assigning our special event handler to iframe */ 
var iframe = $('iframe[src="login.htm"]')[0],
    iDoc = iframe.contentWindow || iframe.contentDocument; // we love IE
if (iDoc.document && iDoc.document.body) {
    $(iDoc.document.body).bind('contentchange', function(){
        var currentHeight = $(this).outerHeight();
        // we need to change iframe height as well as dialogs height
        iframe.height = currentHeight;
        $('#loginDialog').height(currentHeight);
    })
}    
/* end */

Sorry, haven't tested for myself, but (I feel) it'll work. Hope it helps.

Mushex Antaranian
Thanks a bunch for writing this up. Unfortunately outerHeight() is returning 0 all the time. And I'm not sure the contentchange test will work, since the DOM doesn't change... just the styles of existing elements in order to make them appear/disappear. Can you advise?
Andrew Arnott
To solve the problem with outerHeight == 0, try wrap content of body in iframe into a block element like div, and then just catch `contentchange` event for `$(iDoc.document.body).find('div:first')` . Please let me know if it works.
Mushex Antaranian