views:

621

answers:

1

<iframe name="asdf" id="asdf" onload="change_height(this)" src="asdf.jsp" width="250" scrolling="no" frameborder="0"></iframe>

        function change_height(iframe) {
            if (document.all) {
                // IE.
                ieheight = iframe.document.body.scrollHeight;
                iframe.style.height = ieheight;
            } else {
                // Firefox.
                ffheight= iframe.contentDocument.body.offsetHeight;
                iframe.style.height = ffheight+ 'px';

            }
        }

ieheight is twice the actual height when this runs in IE7; haven't tested on IE6. It's the same value if I use scrollHeight or offsetHeight.

It's the correct height in Firefox.

Before I patch this by just dividing the IE value /2, what's the right way to do this?

+4  A: 

document.body represents the viewport when IE is running in Quirks Mode. If the document inside your iframe is in Quirks, the scrollHeight of the body will be equal to the height of its viewport, ie. the default height of the iframe.

If you really needed to get the document-height in Quirks Mode you would have to add an extra wrapper div to measure. A much better fix is to make sure all your documents use a Standards Mode doctype. You shouldn't be authoring anything with Quirks Mode in this decade.

Also, you shouldn't use document.all for IE sniffing (this may go wrong for other browsers that support it), you shouldn't use iframe.document (it's non-standard and not even documented by MSDN), and you should always add 'px' units (IE can cope with it fine and you need it in Standards Mode).

function change_height(iframe) {
    var doc= 'contentDocument' in iframe? iframe.contentDocument : iframe.contentWindow.document;
    iframe.style.height= doc.body.offsetHeight+'px';
}
bobince
In IE7, that's just giving me the pre-existing height of the window, not the size of its contents. Help? :-)
Dean J
As I said, that's what will happen in Quirks Mode. In Standards Mode, `body` is really the height of the content in the `<body>` element. Don't use Quirks Mode. It's not nice.
bobince
I don't have full control of the content in the iframe, it's someone in another group, I'll have to get them to help me. That aside, Thank You!
Dean J
If anyone's followed this so far, the following link helped clear up which DOCTYPE headers trigger quirks mode, and which don't: http://hsivonen.iki.fi/doctype/
Dean J