By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,605 Members | 2,137 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,605 IT Pros & Developers. It's quick & easy.

How to do proper object detection

P: n/a
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.

Jul 20 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a


de*******@no.spam.com wrote:
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;
--

Martin Honnen
http://JavaScript.FAQTs.com/

Jul 20 '05 #2

P: n/a
Thanks for the reply, Martin.

Jul 20 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.