ScrollTop always returns 0

I tried using scrollTop as well as scrollTop () and it always returns 0. As possible, I tried this as follows:

Template.myHome.events({ "click .examine": function(event){ event.preventDefault(); varPos = event.clientY; var yPos = document.body.scrollTop; console.log("Y coords: " + yPos); } }); 

as well as using the jQuery version on multiple divs inside and including the body tag, again everything, giving me 0 or null.

All I just want is to get the number of pixels moved along the y axis as the user scrolls down the page.

+5
source share
3 answers

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> 
+10
source

This covers both the html element and the body element, a cross browser (tested on Chrome / Canary, FF, Edge, IE11)

 function getScrollTop() { alert(Math.max(document.body.scrollTop,document.documentElement.scrollTop)); } 
 Bla <br><br><br><br><br> Bla <br><br><br><br><br> Bla <br><br><br><br><br> Bla <br><br><br><br><br> <button onclick="getScrollTop();">Click me</button> 
+1
source

to try

  $("html, body").scrollTop(); 
0
source

Source: https://habr.com/ru/post/1245791/


All Articles