How to do proper object detection

D

delerious

I've read that IE 5/5.5 stores elements such as scrollLeft and scrollTop in
the document.body object, and IE6 stores those elements in the
document.documentElement object.

I wrote up the following javascript function:

function getScrollTop() {
var s = 0;
if (document.documentElement && typeof(document.documentElement.scrollTop)
!= 'undefined') {
s = document.documentElement.scrollTop;
}
else if (document.body && typeof(document.body.scrollTop) != 'undefined') {
s = document.body.scrollTop;
}
return s;
}

But that didn't work as document.documentElement.scrollTop is actually defined
in IE 5.5 (it always returns 0 though).

So I rewrote it like this:

function getScrollTop() {
var s = 0;
if (document.documentElement && document.documentElement.scrollTop) {
s = document.documentElement.scrollTop;
}
else if (document.body && document.body.scrollTop) {
s = document.body.scrollTop;
}
return s;
}

That works, but if the page hasn't scrolled at all, then it is only working by
accident. If the page hasn't scrolled at all, the code within both the if
clause and the else-if clause are not executed, because the scrollTop has a
number value of 0, and javascript treats a 0 number value as false. So the
function isn't really working correctly, but it is returning the correct value
since the s variable is initialized to 0. If the s variable were initialized
to 10, then the function would return the wrong value.

I am wondering how I can get IE to go into the proper if/else-if clause.
 
M

Martin Honnen

I've read that IE 5/5.5 stores elements such as scrollLeft and scrollTop in
the document.body object, and IE6 stores those elements in the
document.documentElement object.

That is not correct, the properties exist on both element objects, only
if you want to know the scroll position of the viewport then you need to
check the right element.
That is document.body with IE5/5.5 in any case but with IE6 it depends
on document.compatMode whether document.body or document.documentElement
is the right element to look at:
var scrollLeft;
if (typeof document.compatMode != 'undefined' &&
document.compatMode != 'BackCompat')
scrollLeft = document.documentElement.scrollLeft;
else
scrollLeft = document.body.scrollLeft;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top