Note that there are some explanatory texts on larger screens.

plurals
  1. PODeterminating location of span element for absolute positioning of floating div
    primarykey
    data
    text
    <p>I need to create a "popup" div over a span element.</p> <p>I try to determinate its position and size to give correct boundary to place floating div.</p> <pre><code> &lt;html&gt; &lt;body&gt; &lt;p&gt;text a&lt;/p&gt; &lt;div style="padding-left:200px;padding-top:500px"&gt; &lt;table class="message"&gt; &lt;tr&gt;&lt;td&gt;test &lt;span id="test"&gt;hello&lt;/span&gt; world&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I try to get this information for an element <code>id=test</code></p> <p>I tried two methods:</p> <p>First I get span</p> <pre><code>var span = document.getElementById('test'); </code></pre> <p>Than I calculate either using approach proposed at <a href="https://stackoverflow.com/questions/442404/dynamically-retrieve-the-position-x-y-of-an-html-element">Retrieve the position (X,Y) of an HTML element</a></p> <pre><code>var x0 = 0; var y0 = 0; var el = span; while(el &amp;&amp; !isNaN(el.offsetLeft) &amp;&amp; !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; </code></pre> <p>And I also try it by using:</p> <pre><code>var rect = span.getBoundingClientRect(); x0 = rect.left; x1 = rect.right; y0 = rect.top; y1 = rect.bottom; </code></pre> <p>Than I log:</p> <pre><code> console.log(JSON.stringify([x0,x1,y0,y1])); </code></pre> <p>In both cases I get:</p> <pre><code>[236,264,381,401] </code></pre> <p>Which can't be correct as the margin above the table of 500 pixels.</p> <p>How can I solve this problem correctly?</p> <p>i.e. how can I put a <code>div</code> with <code>position:ablosute</code> over this element at correct location?</p> <p><strong>Note:</strong> I can't use JQuery or other fat toolkits, I rather need a portable solution in plane JavaScript.</p> <p><strong>Edit:</strong> 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?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload