5 Internet Explorer: scrollTop vs DOCTYPE

Posted: Nov 23, 2005, under DHTML. Updated: Dec 2, 2005. Add a comment!

I’ve had quite a bit of “fun” today, trying to figure out why my sidebar slider doesn’t work in Explorer. Funniest thing was, it worked perfectly when I tested it in a mockup HTML file. Turns out document.body.scrollTop would always return 0, so the slider just sat there instead of detecting scroll movements.

So I assumed that something broke it when it went online. Was it WordPress? Was it some weird specification in Explorer? (it wasn’t, as far as MSDN cold tell). Explorer issues no JavaScript errors. It just returned 0 instead of proper values.

I ended up saving the HTML to disk and deleting bits of it to see when the slider would start working again (actually, when scrollTop would start working again).

Within seconds, I had my answer. It was the DOCTYPE declaration. You know, the HTML conformity declaration, fairly standard stuff. As soon as it was gone, scrollTop worked fine again.

Update: Thanks to this, I got a pure JavaScript solution, as well as an explanation. A DOCTYPE declaration puts Explorer into “strict” mode, at which point version 6 relegates scrollTop from under document.body to document.documentElement. Now, that makes perfect sense. Not. :tongue:

So, grabbing scrollTop actually involves something like this in order to be truly crossbrowser:

var top = (document.documentElement && document.documentElement.scrollTop) ?
  document.documentElement.scrollTop : document.body.scrollTop;