I am trying to detect the supported version for document.x.scrollTop
for the browser. I have the following code:
var scrollTopElem = document.documentElement;
// Cannot do `document.documentElement.scrollTop || document.body.scrollTop` i.e. `||`
// because if the actual scrollTop is 0 right now, then I won't get the supported `document.x` type.
if (scrollTopElem.scrollTop === 0) {
var t = scrollTopElem.scrollTop;
// Add 1 to `scrollTopElem`
++scrollTopElem.scrollTop;
// Check to see if `scrollTopElem` applied the addition.
// If not, `document.documentElement.scrollTop` isn't supported
scrollTopElem = t + (1 === scrollTopElem.scrollTop--) ? scrollTopElem : document.body;
}
Which I got from this answer in the first function, scrollTo
. I added the comments myself, which I hope is accurate.
The only time t
is being used, is to add t + (documentBody || body)
. That doesn't make sense since t
is a number, and (documentBody || body)
is an element. So how can you add a number to an element?
My question is: Is the variable t
necessary, and what is it doing, what's the point of it? Also, is there a better way to detect the supported document.x.scrollTop
?
Is there a better way of detecting which is the supported way?
W3schools does the following (at their last example, the function called myFunction
:
document.body.scrollTop + document.documentElement.scrollTop
The 'problem' with that, is that it's kind of hackish. It's not a direct solution, but a roundabout way to answer it. Also, performance-wise, the first way I mentioned is better (i.e. if I will use scrollTop
more than once, which I will).