Depending on the implementation, the element that scrolls through the document may be <html>
or <body>
.
CSSOM View represents document.scrollingElement
(see mail flow ) that returns the corresponding element:
document.scrollingElement.scrollTop;
Alternatively, you can use window.scrollY
or window.pageYOffset
. They are aliases and return the same value, but the latter has great browser support.
For browsers that do not support any of the above, you can check both of them:
document.documentElement.scrollTop; document.body.scrollTop;
var scrollTests = document.getElementById('scrollTests'); var tests = [ "document.body.scrollTop", "document.documentElement.scrollTop", "document.scrollingElement.scrollTop", "window.scrollY", "window.pageYOffset" ]; for(var i=0; i<tests.length; ++i) { var p = scrollTests.appendChild(document.createElement('p')); p.appendChild(document.createTextNode(tests[i] + ' = ')); p.appendChild(document.createElement('span')).id = tests[i]; } window.onscroll = function() { for(var i=0; i<tests.length; ++i) { try{ var val = eval(tests[i]); } catch(err) { val = '[Error]'; } document.getElementById(tests[i]).innerHTML = val; } };
#scrollTests { position: fixed; top: 0; } body:after { content: ''; display: block; height: 999999px; }
<div id="scrollTests"></div>
source share