Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In general, assuming you have an element named <code>elem</code>, it's actually quite easy to get the X and Y coordinates of the top-left corners of an element, assuming you want these in <em>document coordinates</em>. In all browsers this is returned by the <code>elem.offsetLeft</code> and <code>elem.offsetTop</code> properties.</p> <p>The only trick you have to be aware of is that if <code>elem</code> is absolutely positioned in another element, say a <code>div</code> with a left / top margin of 20px, these properties will return 0, as it only takes into account the current element and not the entire chain of elements. Luckily we can use a "chain-traversal" function to capture all of the margins of elements associated with a given element, tally them up to get the correct document coordinates.</p> <p>As Sime Vidas mentioned, there is also JQuery's <code>position()</code> and <code>offset()</code> properties, in this case you would want the <code>offset()</code> properties.</p> <p>You can also use the <code>getBoundingClientRect()</code> method, however this returns the coordinates of an element relative to its <code>offsetParent</code> and thus is not entirely reliable. Look at the following examples:</p> <pre><code>// getPosition function function getPosition(elem){ var dims = {offsetLeft:0, offsetTop:0}; do { dims.offsetLeft += elem.offsetLeft; dims.offsetTop += elem.offsetTop; } while (elem = elem.offsetParent); return dims; } cont1.style.position = "absolute"; cont1.style.marginLeft = "10px"; cont2.style.position = "absolute"; cont2.style.marginLeft = "10px"; box.style.position = "absolute"; box.style.marginLeft = "10px"; console.log(getPosition(box).offsetLeft); // returns "30" console.log(getPosition(box).offsetTop); // returns "0" // or in JQuery console.log($(box).offset().left) // also returns "30" console.log($(box).offset().top) // also returns "0" </code></pre> <p>Also I suggest you read <a href="http://www.quirksmode.org/js/findpos.html" rel="nofollow">this</a>.</p>
    singulars
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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