Search code examples
javascriptpositionviewport

Why window.scrollY + element.getBoundingClientRect().top is not equal to element.offsetTop?


I expected element.getBoundingClientRect(), window.scrollY and element.offsetTop to work as shown on the picture below. But as you can see, the numbers do not add up (in my case, pos.offsetTop - (el.getBoundingClientRect().top + window.scrollY) always == -14).

What am I doing wrong?

Figre 1


Solution

  • This might be due to the structure of your page. If you look at the following example, you will see that the offsetTop of the internal div is still 51 even though it is over 150px away from the top of the page.

    var element = document.getElementById("id");
    console.log(element.offsetTop)
    <table style="margin-top: 100px;">
      <tr>
        <td>
          <div style="margin-top: 50px;background-color:blue; height:100px;">
    
            <div id="id" style="background-color: red; width: 20px; height:20px;">
            </div>
          </div>
        </td>
      </tr>
    </table>

    This is due to the fact that the parent element of the div is the table object and the distance from the top of the div to its parent is 51px.

    Take a look at this page for some more in-depth talking about offsetTop (https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop)

    And this page for the offsetParent (https://developer.mozilla.org/en-US/docs/Web/API/HTMLelement/offsetParent)