Wednesday, August 03, 2005

The dark despair of DOCTYPEs

It bears repeating: the use of different DOCTYPEs can change the DOM interface in unexpected ways. It shouldn't, but it does. To wit:

document.body.scrollTop
becomes
document.documentElement.scrollTop
...depending on which DOCTYPE is used. (The former property doesn't disappear, but stops being updated, returning 0 (zero) no matter how much you scroll). This seems to be true for both IE6 and Firefox. So be sure to test for both if your web app depends on accurately measuring the scroll offset of a page. Double-especially if your app is something to be dropped into existing webpages with DOCTYPEs you cannot know in advance.

IE has a neato

document.compatMode
property that returns "BackCompat" if the DOCTYPE is allowing the page to behave like old-school IE, with the broken box model and the stuff and the thing. "CSS1Compat" indicates DOCTYPE-triggered "standards-compliance" mode. So you can have your app test for this and adjust accordingly.

4 Comments:

At 5:55 PM, Blogger John said...

Sounds familiar. I went through this just recently when resizing an iframe. Some pages were rendering in quirks mode (triggered by a comment tag before the doctype). There's not much documentation out there either.

 
At 7:19 PM, Blogger David said...

top = document.documentElement.scrollTop || document.body.scrollTop || 0;

 
At 6:06 PM, Blogger scottandrew said...

Beware of doing a boolean check for document.documentElement.scrollTop. Remember, scrollTop usually starts out at zero, which means a check for document.documentElement.scrollTop can return zero and thus evaluate to false.

I think it's safer to check for document.documentElement alone.

 
At 10:18 PM, Blogger David said...

Scott-

My way should work assuming that document.documentElement and document.body are at least defined. You'd use that statement every time you grab the top and you should get the correct value. Putting document.body.scrollTop first might be preferable though.

 

Post a Comment

<< Home