I need to create a "popup" div over a span element.
I try to determinate its position and size to give correct boundary to place floating div.
<html>
<body>
<p>text a</p>
<div style="padding-left:200px;padding-top:500px">
<table class="message">
<tr><td>test <span id="test">hello</span> world</td></tr>
</table>
</div>
</body>
</html>
I try to get this information for an element id=test
I tried two methods:
First I get span
var span = document.getElementById('test');
Than I calculate either using approach proposed at Retrieve the position (X,Y) of an HTML element
var x0 = 0;
var y0 = 0;
var el = span;
while(el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
x0 += el.offsetLeft - el.scrollLeft;
y0 += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
var x1 = x0 + span.offsetWidth;
var y1 = y0 + span.offsetHeight;
And I also try it by using:
var rect = span.getBoundingClientRect();
x0 = rect.left;
x1 = rect.right;
y0 = rect.top;
y1 = rect.bottom;
Than I log:
console.log(JSON.stringify([x0,x1,y0,y1]));
In both cases I get:
[236,264,381,401]
Which can't be correct as the margin above the table of 500 pixels.
How can I solve this problem correctly?
i.e. how can I put a div
with position:ablosute
over this element at
correct location?
Note: I can't use JQuery or other fat toolkits, I rather need a portable solution in plane JavaScript.
Edit: I noted that it does not work if the page requires scolling, i.e. the head part of page is hidden, how can it be compensated?