Search code examples
javascriptscrolltop

Why am I not getting the scrollTop value?


I want to get the scrollTop value of an element so I can trigger other things depending on that. The client should always check the scrollTop value, so I am using onscroll to run the function. It does not work, I always get 0.

<!DOCTYPE html>
<html>
<head></head>
<body onscroll="get_y_pos();">
  <div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>
  <div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>
  <div id="element_to_watch" style="height: 400px; width: 300px; background: blue; margin: 20px;"></div>
  <div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>
  <div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>
</body>
  <script>
    function get_y_pos() {
      var pos = document.getElementById('element_to_watch').scrollTop;
      console.log(pos);
    }
  </script>
</html>


Solution

  • As stated by @bertida, to achieve this, getBoundingClientRect().top should be used instead of scrollTop.

    <!DOCTYPE html>
    <html>
    <head></head>
    <body onscroll="get_y_pos();">
      <div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>
      <div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>
      <div id="element_to_watch" style="height: 400px; width: 300px; background: blue; margin: 20px;"></div>
      <div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>
      <div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>
    </body>
      <script>
        function get_y_pos() {
          var pos = document.getElementById('element_to_watch').getBoundingClientRect().top;
          console.log(pos);
        }
      </script>
    </html>