Using javascript how to get element position

as the title says, how to get the x, y elements relative to their location on the web page and their positioning schemes, such as absolute, relative, etc.

+3
source share
3 answers

In a modern browser, getBoundingClientRect and getClientRects will give you direct objects that describe your element. See https://developer.mozilla.org/en/DOM/element.getBoundingClientRect and https://developer.mozilla.org/en/DOM/element.getClientRects

If you need to work with IE8, you will need to do different things in different browsers in order to get the correct answers (for example, object-detect getBoundingClientRect and abandon some other method if it is not present).

Calculating jQuery offset()and Quirksmode findPoswill give incorrect answers in any browser that does sub-pixel positioning (e.g. Firefox or IE9), because they will round the answer to an integer number of pixels. Depending on what you are doing, this may or may not be normal.

+6
source

Using jQuery:

var $elt = $('select an element however'),
    cssPosition = $elt.css('position'),
    offset = $elt.offset(),
    top = offset.top,
    left = offset.left;

Without jQuery, use the Quirksmode FunctionfindPos :

var elt = document.getElementBy...,
    pos = findPos(elt),
    top = pos[1],
    left = pos[0];

Getting the calculated CSS value positionwithout a library is another worm out of worms . It comes down to:

+5

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">&nbsp;TEST</div>

:

alert(findPos(document.getElementById('ser')));

,

+4
source

All Articles