Retrieve the position (X,Y) of an HTML element

  1. Home
  2. javascript
  3. Retrieve the position (X,Y) of an HTML element

I want to know how to get the X and Y position of HTML elements such as img and div in JavaScript.

First answer

Second answer

This worked for me (modified from highest voted answer):

function getOffset(el) {
  const rect = el.getBoundingClientRect();
  return {
    left: rect.left + window.scrollX,
    top: rect.top + window.scrollY
  };
}

Using this we can call

getOffset(element).left

or

getOffset(element).top

Third answer

If page includes – at least- any “DIV”, the function given by meouw throws the “Y” value beyond current page limits. In order to find the exact position, you need to handle both offsetParent’s and parentNode’s.

Try the code given below (it is checked for FF2):


var getAbsPosition = function(el){
    var el2 = el;
    var curtop = 0;
    var curleft = 0;
    if (document.getElementById || document.all) {
        do  {
            curleft += el.offsetLeft-el.scrollLeft;
            curtop += el.offsetTop-el.scrollTop;
            el = el.offsetParent;
            el2 = el2.parentNode;
            while (el2 != el) {
                curleft -= el2.scrollLeft;
                curtop -= el2.scrollTop;
                el2 = el2.parentNode;
            }
        } while (el.offsetParent);

    } else if (document.layers) {
        curtop += el.y;
        curleft += el.x;
    }
    return [curtop, curleft];
};
Reprint:https://stackoverflow.com/questions/442404/retrieve-the-position-x-y-of-an-html-element
Spread the love

Related articles

Comments are closed.