Search code examples
javascripthtmlcsstooltipchart.js

getBoundingClientRect gives incorrect value


I am using custom tooltips for ChartJS and to position the tooltips I need to use getBoundingClientRect to get the position of the chart and then I move the tooltip relative to that location. However, the positions returned from getBoundingClientRect are not representative of the actual div. There is no padding, no margin, etc. This red box indicates the actual div border and the green is the box returned from getBoundingRect

Any idea why this is and how to fix it? My page changes a bit on resize so I can't just hard code -150px or whatever.


Solution

  • The issue was that getBoundingClientRect was taking into account the margin of my overall content wrapper. This wrapper's margin is changed when the page is resized to better fit the contents and thus getBoundingClientRect would also change it's output. I'm not sure why it took into account just this one div's margin, but I just subtracted the margin from the top and left values to fix my issue.