Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find X/Y of an HTML element with JavaScript [duplicate]

People also ask

How do you find the X and Y coordinates of an HTML element?

The position of (X, Y) means the co-ordinate of an element at the top-left point in a document. X represent the horizontal position and Y represent the vertical position. Use element. getBoundingClientRect() property to get the position of an element.

How do you find the coordinates of an element in HTML?

jQuery . offset() will get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.

How do you find XY coordinates of a div?

If the element is in the main document you can get the DIV's coordinates with... var X=window. getComputedStyle(abc,null). getPropertyValue('left'); var Y=window.

How do you repeat the same element in HTML?

Add the repeat-element attribute to the element you want to duplicate and specify the number of times to copy. Use the repeat-text attribute if you only want to duplicate the text within the element.


Here's how I do it:

// Based on: http://www.quirksmode.org/js/findpos.html
var getCumulativeOffset = function (obj) {
    var left, top;
    left = top = 0;
    if (obj.offsetParent) {
        do {
            left += obj.offsetLeft;
            top  += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    return {
        x : left,
        y : top
    };
};

That can be tricky depending on browser and version. I would suggest using jQuery and the positions plugin.


You can use a library such as Prototype or jQuery, or you can use this handy function:

It returns an array.

myPos = findPos(document.getElementById('something'))
x = myPos[0]
y = myPos[1]

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];
}

For what it's worth, here's a recursive version:

function findPos(element) {
  if (element) {
    var parentPos = findPos(element.offsetParent);
    return [
      parentPos.X + element.offsetLeft,
      parentPos.Y + element.offsetTop
    ];
  } else {
    return [0,0];
  }
}

You can add two properties to the Element.prototype to get top/left of any element.

window.Object.defineProperty( Element.prototype, 'documentOffsetTop', {
    get: function () { return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop : 0 ); }
} );

window.Object.defineProperty( Element.prototype, 'documentOffsetLeft', {
    get: function () { return this.offsetLeft + ( this.offsetParent ? this.offsetParent.documentOffsetLeft : 0 ); }
} );

Here's a demo comparing the results to jQuery's offset().top and .left: http://jsfiddle.net/ThinkingStiff/3G7EZ/