like the title says, how to get the element's x, y positions with respect to their location in the web page and their positioning schemes like absolute, relative etc.
3 Answers
In a modern browser, getBoundingClientRect and getClientRects will give you rect objects describing your element. See https://developer.mozilla.org/en/DOM/element.getBoundingClientRect and https://developer.mozilla.org/en/DOM/element.getClientRects
If you have to work with IE8, then you'll have to do different things in different browsers to get correct answers (e.g. object-detect getBoundingClientRect and fall back on some other method if it's not present).
The jQuery offset()
calculation and the Quirksmode findPos
will give incorrect answers in any browser that does subpixel positioning (e.g. Firefox or IE9), because they will round the answer to an integer number of pixels. Depending on what you're doing, that may or may not be ok.

- 34,758
- 5
- 52
- 55
With jQuery:
var $elt = $('select an element however'),
cssPosition = $elt.css('position'),
offset = $elt.offset(),
top = offset.top,
left = offset.left;
Without jQuery, use Quirksmode's findPos
function:
var elt = document.getElementBy...,
pos = findPos(elt),
top = pos[1],
left = pos[0];
Getting the computed CSS position
value without a library is another can of worms. It boils down to:
element.currentStyle
(IE)getComputedStyle(element)
(real browsers)
-
4I appreciate the comment, but... how is my answer _not_ JavaScript? jQuery is JavaScript, and I also showed how to do it without jQuery. – Matt Ball May 26 '11 at 23:06
-
jQuery's positioning isn't always correct, and PPK's version is simplilstic - it will fail in some cases. Browsers have various positioning quirks, IE's strict, compat and quirks modes add to the mix. Keep things simple and life is much easier. – RobG May 27 '11 at 00:50
-
@RobG so what do you suggest instead? I've never really had issues with jQuery's algorithm. – Matt Ball May 31 '11 at 16:57
Check out this
JS:
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}
return [curleft,curtop];
}
HTML:
<div id="ser"> TEST</div>
RETURN CALL:
alert(findPos(document.getElementById('ser')));
I hope its help to you

- 3,068
- 2
- 28
- 31
-
FYI: that snippet contains an error. The variable "curtop" is contaminating global scope. I wrote to the guy at quirksmode.org about it just now. http://www.quirksmode.org/js/findpos.html – Jakob Sternberg Aug 12 '14 at 04:21