getBoundingClientRect top property returns wrong value?

Viewed 3871

I'm getting in console top, left , right, bottom properties of div element:

var offSet = document.getElementById("div").getBoundingClientRect();  

Why do I get top 84 px instead of 8px?

Here's an example : https://codepen.io/Y-Taras/pen/zPjrWJ

P.S. to see in the console 4 properties click anywhere at the page

1 Answers

In the CodePen, the script in the body is executed before the onload event is fired. So the info you get from the div (in the global offSet variable) is from the position it's in before the draggable function has changed the span to position absolute.

(You can see this by, for instance, adding alert() in the code just before assigning offSet. Then program execution pauses when the div is still below the span.)

Solution: fetch the offSet information inside the onmouseup function, or in the onload event.

Related